Skip to content

Commit a73aa24

Browse files
committed
Add fast path for shrinking realloc()
When realloc() is called with a smaller size than the current block, we can avoid allocating a new block and copying data. Instead, split the existing block into two smaller blocks using the split_block() helper. This fast path improves performance for shrinking realloc() calls and triggers selective coalescing only when fragmentation exceeds the threshold.
1 parent b0fbaf7 commit a73aa24

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

lib/malloc.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,16 @@ void *realloc(void *ptr, uint32_t size)
278278
old_size - size < sizeof(memblock_t) + MALLOC_MIN_SIZE)
279279
return ptr;
280280

281+
/* fast path for shrinking */
282+
if (size <= old_size) {
283+
split_block(old_block, size);
284+
/* Trigger coalescing only when fragmentation is high */
285+
if (free_blocks_count > COALESCE_THRESHOLD)
286+
selective_coalesce();
287+
CRITICAL_LEAVE();
288+
return (void *) (old_block + 1);
289+
}
290+
281291
void *new_buf = malloc(size);
282292
if (new_buf) {
283293
memcpy(new_buf, ptr, min(old_size, size));

0 commit comments

Comments
 (0)