Skip to content

Commit def6e7d

Browse files
author
icgmilk
committed
Optimize hashmap memory allocation with arena
Replace malloc with arena allocation for 'hashmap_node_t' and key strings, while keeping the 'hashmap_t' structure allocated with malloc. This hybrid approach reduces memory fragmentation for frequently allocated small objects and preserves compatibility with existing rehash functionality.
1 parent 11785eb commit def6e7d

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

src/globals.c

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ type_t *TY_int;
5050
/* Arenas */
5151

5252
arena_t *INSN_ARENA;
53-
53+
arena_t *HASHMAP_ARENA;
5454
/* BLOCK_ARENA is responsible for block_t / var_t allocation */
5555
arena_t *BLOCK_ARENA;
5656

@@ -378,15 +378,15 @@ hashmap_node_t *hashmap_node_new(char *key, void *val)
378378
return NULL;
379379

380380
int len = strlen(key);
381-
hashmap_node_t *node = malloc(sizeof(hashmap_node_t));
381+
hashmap_node_t *node = arena_alloc(HASHMAP_ARENA, sizeof(hashmap_node_t));
382382

383383

384384
if (!node) {
385385
printf("Failed to allocate hashmap_node_t\n");
386386
return NULL;
387387
}
388388

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

391391
if (!node->key) {
392392
printf("Failed to allocate hashmap_node_t key with size %d\n", len + 1);
@@ -526,16 +526,6 @@ void hashmap_free(hashmap_t *map)
526526
if (!map)
527527
return;
528528

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-
539529
free(map->buckets);
540530
free(map);
541531
}
@@ -1073,6 +1063,7 @@ void global_init(void)
10731063
BLOCK_ARENA = arena_init(DEFAULT_ARENA_SIZE);
10741064
INSN_ARENA = arena_init(DEFAULT_ARENA_SIZE);
10751065
BB_ARENA = arena_init(DEFAULT_ARENA_SIZE);
1066+
HASHMAP_ARENA = arena_init(DEFAULT_ARENA_SIZE);
10761067
PH2_IR_FLATTEN = malloc(MAX_IR_INSTR * sizeof(ph2_ir_t *));
10771068
SOURCE = strbuf_create(MAX_SOURCE);
10781069
FUNC_MAP = hashmap_create(DEFAULT_FUNCS_SIZE);
@@ -1095,6 +1086,7 @@ void global_release(void)
10951086
arena_free(BLOCK_ARENA);
10961087
arena_free(INSN_ARENA);
10971088
arena_free(BB_ARENA);
1089+
arena_free(HASHMAP_ARENA);
10981090
free(PH2_IR_FLATTEN);
10991091
strbuf_free(SOURCE);
11001092
hashmap_free(FUNC_MAP);

0 commit comments

Comments
 (0)