Skip to content

Commit 0f9bdcc

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 6d1a20a commit 0f9bdcc

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
@@ -636,19 +636,36 @@ void *malloc(int size)
636636
__freelist_head->size = -1;
637637
}
638638

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

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

@@ -771,7 +788,7 @@ void free(void *ptr)
771788
__alloc_tail = prev;
772789
}
773790

774-
/* Insert head in __freelist_head */
791+
/* Insert at head of freelist */
775792
cur->next = __freelist_head;
776793
cur->prev = NULL;
777794
chunk_set_freed(cur);

0 commit comments

Comments
 (0)