Skip to content

Commit e04a60d

Browse files
authored
Merge pull request #222 from icgmilk/fix_hashmap
Optimize hashmap memory allocation with arena
2 parents 7378a52 + 63eab00 commit e04a60d

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

src/globals.c

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ type_t *TY_int;
5151

5252
arena_t *INSN_ARENA;
5353

54+
/* HASHMAP_ARENA is responsible for hashmap_node_t allocation */
55+
arena_t *HASHMAP_ARENA;
56+
5457
/* BLOCK_ARENA is responsible for block_t / var_t allocation */
5558
arena_t *BLOCK_ARENA;
5659

@@ -378,15 +381,15 @@ hashmap_node_t *hashmap_node_new(char *key, void *val)
378381
return NULL;
379382

380383
int len = strlen(key);
381-
hashmap_node_t *node = malloc(sizeof(hashmap_node_t));
384+
hashmap_node_t *node = arena_alloc(HASHMAP_ARENA, sizeof(hashmap_node_t));
382385

383386

384387
if (!node) {
385388
printf("Failed to allocate hashmap_node_t\n");
386389
return NULL;
387390
}
388391

389-
node->key = calloc(len + 1, sizeof(char));
392+
node->key = arena_alloc(HASHMAP_ARENA, len + 1);
390393

391394
if (!node->key) {
392395
printf("Failed to allocate hashmap_node_t key with size %d\n", len + 1);
@@ -526,16 +529,6 @@ void hashmap_free(hashmap_t *map)
526529
if (!map)
527530
return;
528531

529-
for (int i = 0; i < map->size; i++) {
530-
for (hashmap_node_t *cur = map->buckets[i], *next; cur; cur = next) {
531-
next = cur->next;
532-
free(cur->key);
533-
free(cur->val);
534-
free(cur);
535-
cur = next;
536-
}
537-
}
538-
539532
free(map->buckets);
540533
free(map);
541534
}
@@ -1073,6 +1066,7 @@ void global_init(void)
10731066
BLOCK_ARENA = arena_init(DEFAULT_ARENA_SIZE);
10741067
INSN_ARENA = arena_init(DEFAULT_ARENA_SIZE);
10751068
BB_ARENA = arena_init(DEFAULT_ARENA_SIZE);
1069+
HASHMAP_ARENA = arena_init(DEFAULT_ARENA_SIZE);
10761070
PH2_IR_FLATTEN = malloc(MAX_IR_INSTR * sizeof(ph2_ir_t *));
10771071
SOURCE = strbuf_create(MAX_SOURCE);
10781072
FUNC_MAP = hashmap_create(DEFAULT_FUNCS_SIZE);
@@ -1095,6 +1089,7 @@ void global_release(void)
10951089
arena_free(BLOCK_ARENA);
10961090
arena_free(INSN_ARENA);
10971091
arena_free(BB_ARENA);
1092+
arena_free(HASHMAP_ARENA);
10981093
free(PH2_IR_FLATTEN);
10991094
strbuf_free(SOURCE);
11001095
hashmap_free(FUNC_MAP);

0 commit comments

Comments
 (0)