Skip to content

Optimize hashmap memory allocation with arena #222

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions src/globals.c
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ type_t *TY_int;

arena_t *INSN_ARENA;

/* HASHMAP_ARENA is responsible for hashmap_node_t allocation */
arena_t *HASHMAP_ARENA;

/* BLOCK_ARENA is responsible for block_t / var_t allocation */
arena_t *BLOCK_ARENA;

Expand Down Expand Up @@ -378,15 +381,15 @@ hashmap_node_t *hashmap_node_new(char *key, void *val)
return NULL;

int len = strlen(key);
hashmap_node_t *node = malloc(sizeof(hashmap_node_t));
hashmap_node_t *node = arena_alloc(HASHMAP_ARENA, sizeof(hashmap_node_t));


if (!node) {
printf("Failed to allocate hashmap_node_t\n");
return NULL;
}

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

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

for (int i = 0; i < map->size; i++) {
for (hashmap_node_t *cur = map->buckets[i], *next; cur; cur = next) {
next = cur->next;
free(cur->key);
free(cur->val);
free(cur);
cur = next;
}
}

free(map->buckets);
free(map);
}
Expand Down Expand Up @@ -1073,6 +1066,7 @@ void global_init(void)
BLOCK_ARENA = arena_init(DEFAULT_ARENA_SIZE);
INSN_ARENA = arena_init(DEFAULT_ARENA_SIZE);
BB_ARENA = arena_init(DEFAULT_ARENA_SIZE);
HASHMAP_ARENA = arena_init(DEFAULT_ARENA_SIZE);
PH2_IR_FLATTEN = malloc(MAX_IR_INSTR * sizeof(ph2_ir_t *));
SOURCE = strbuf_create(MAX_SOURCE);
FUNC_MAP = hashmap_create(DEFAULT_FUNCS_SIZE);
Expand All @@ -1095,6 +1089,7 @@ void global_release(void)
arena_free(BLOCK_ARENA);
arena_free(INSN_ARENA);
arena_free(BB_ARENA);
arena_free(HASHMAP_ARENA);
free(PH2_IR_FLATTEN);
strbuf_free(SOURCE);
hashmap_free(FUNC_MAP);
Expand Down