Skip to content

Commit 2134290

Browse files
committed
Add fast path for growing realloc()
When realloc() needs a larger size, we can check if the next block is free and adjacent. If the combined size of the current and next block is sufficient, merge them into a single block and split it to the desired size. This fast path avoids allocating a new block and copying data, and selective coalescing is triggered only when fragmentation exceeds the threshold, improving performance for growing realloc() calls.
1 parent a73aa24 commit 2134290

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

lib/malloc.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,23 @@ void *realloc(void *ptr, uint32_t size)
288288
return (void *) (old_block + 1);
289289
}
290290

291+
/* fast path for growing */
292+
if (old_block->next && !IS_USED(old_block->next) &&
293+
GET_SIZE(old_block) + sizeof(memblock_t) + GET_SIZE(old_block->next) >=
294+
size) {
295+
old_block->size = GET_SIZE(old_block) + sizeof(memblock_t) +
296+
GET_SIZE(old_block->next);
297+
old_block->next = old_block->next->next;
298+
free_blocks_count--;
299+
split_block(old_block, size);
300+
/* Trigger coalescing only when fragmentation is high */
301+
if (free_blocks_count > COALESCE_THRESHOLD)
302+
selective_coalesce();
303+
CRITICAL_LEAVE();
304+
return (void *) (old_block + 1);
305+
}
306+
307+
291308
void *new_buf = malloc(size);
292309
if (new_buf) {
293310
memcpy(new_buf, ptr, min(old_size, size));

0 commit comments

Comments
 (0)