Skip to content

Commit 6ac6076

Browse files
committed
Optimize malloc with hybrid allocation strategy
This commit implements hybrid allocation approach to balance speed and memory efficiency: - First-fit for small allocations (≤64 bytes) for speed optimization - Best-fit for large allocations (>64 bytes) for memory efficiency - Early exit optimization on perfect matches in best-fit search
1 parent 58fdee3 commit 6ac6076

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

lib/c.c

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -637,19 +637,36 @@ void *malloc(int size)
637637
__freelist_head->size = -1;
638638
}
639639

640-
/* Search for the best fit chunk in the free list */
640+
/* Hybrid allocation strategy: first-fit for small, best-fit for large */
641641
chunk_t *best_fit_chunk = NULL;
642642
chunk_t *allocated;
643643
int best_size = 0;
644644

645645
if (!__freelist_head->next) {
646646
allocated = NULL;
647647
} else {
648-
for (chunk_t *fh = __freelist_head; fh->next; fh = fh->next) {
649-
int fh_size = CHUNK_GET_SIZE(fh->size);
650-
if (fh_size >= size && (!best_fit_chunk || fh_size < best_size)) {
651-
best_fit_chunk = fh;
652-
best_size = fh_size;
648+
if (size <= 64) {
649+
/* First-fit for small allocations (speed optimization) */
650+
for (chunk_t *fh = __freelist_head; fh->next; fh = fh->next) {
651+
int fh_size = CHUNK_GET_SIZE(fh->size);
652+
if (fh_size >= size) {
653+
best_fit_chunk = fh;
654+
best_size = fh_size;
655+
break; /* Take first suitable chunk */
656+
}
657+
}
658+
} else {
659+
/* Best-fit for large allocations (memory efficiency) */
660+
for (chunk_t *fh = __freelist_head; fh->next; fh = fh->next) {
661+
int fh_size = CHUNK_GET_SIZE(fh->size);
662+
if (fh_size >= size &&
663+
(!best_fit_chunk || fh_size < best_size)) {
664+
best_fit_chunk = fh;
665+
best_size = fh_size;
666+
/* Early exit on perfect match to avoid useless scanning */
667+
if (best_size == size)
668+
break;
669+
}
653670
}
654671
}
655672

@@ -772,7 +789,7 @@ void free(void *ptr)
772789
__alloc_tail = prev;
773790
}
774791

775-
/* Insert head in __freelist_head */
792+
/* Insert at head of freelist */
776793
cur->next = __freelist_head;
777794
cur->prev = NULL;
778795
chunk_set_freed(cur);

0 commit comments

Comments
 (0)