Skip to content

Commit 38ba45b

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 3c30a17 commit 38ba45b

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
@@ -639,19 +639,36 @@ void *malloc(int size)
639639
__freelist_head->size = -1;
640640
}
641641

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

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

@@ -774,7 +791,7 @@ void free(void *ptr)
774791
__alloc_tail = prev;
775792
}
776793

777-
/* Insert head in __freelist_head */
794+
/* Insert at head of freelist */
778795
cur->next = __freelist_head;
779796
cur->prev = NULL;
780797
chunk_set_freed(cur);

0 commit comments

Comments
 (0)