Preallocate table space for krk_dict_of

This commit is contained in:
K. Lange 2021-03-23 20:25:33 +09:00
parent 49066f7ae2
commit b5c22f77c5
4 changed files with 14 additions and 3 deletions

View File

@ -151,3 +151,13 @@ extern KrkTableEntry * krk_findEntry(KrkTableEntry * entries, size_t capacity, K
*/
extern uint32_t krk_hashValue(KrkValue value);
/**
* @brief Preset the size of a table.
* @memberof KrkTable
*
* Reserves space for a large table.
*
* @param table Table to resize.
* @param capacity Target capacity.
*/
extern void krk_tableAdjustCapacity(KrkTable * table, size_t capacity);

View File

@ -20,6 +20,7 @@ KrkValue krk_dict_of(int argc, KrkValue argv[], int hasKw) {
KrkInstance * outDict = krk_newInstance(vm.baseClasses->dictClass);
krk_push(OBJECT_VAL(outDict));
krk_initTable(&((KrkDict*)outDict)->entries);
krk_tableAdjustCapacity(&((KrkDict*)outDict)->entries, argc);
for (int ind = 0; ind < argc; ind += 2) {
krk_tableSet(&((KrkDict*)outDict)->entries, argv[ind], argv[ind+1]);
}

View File

@ -50,7 +50,7 @@ KrkTableEntry * krk_findEntry(KrkTableEntry * entries, size_t capacity, KrkValue
}
}
static void adjustCapacity(KrkTable * table, size_t capacity) {
void krk_tableAdjustCapacity(KrkTable * table, size_t capacity) {
KrkTableEntry * entries = ALLOCATE(KrkTableEntry, capacity);
for (size_t i = 0; i < capacity; ++i) {
entries[i].key = KWARGS_VAL(0);
@ -75,7 +75,7 @@ static void adjustCapacity(KrkTable * table, size_t capacity) {
int krk_tableSet(KrkTable * table, KrkValue key, KrkValue value) {
if (table->count + 1 > table->capacity * TABLE_MAX_LOAD) {
size_t capacity = GROW_CAPACITY(table->capacity);
adjustCapacity(table, capacity);
krk_tableAdjustCapacity(table, capacity);
}
KrkTableEntry * entry = krk_findEntry(table->entries, table->capacity, key);
int isNewKey = entry->key.type == KRK_VAL_KWARGS;

View File

@ -1,6 +1,6 @@
I am a function.
[42]
{'return': <class 'list'>, 'a': <class 'int'>, 'b': <class 'float'>}
{'a': <class 'int'>, 'b': <class 'float'>, 'return': <class 'list'>}
{'return': None, 'anint': <class 'int'>, 'self': <class '__main__.Foo'>, 'adict': 'dict[str,object]'}
I am a method taking a dict.
None