Skip to content

Commit 279f663

Browse files
committed
Implemented conservative optimizations
1. First-fit threshold optimization: Changed from 64 bytes to 40 bytes for very small allocations - Specifically targets compiler objects like macros, symbols, and constants - Reduces scanning overhead for the most common allocation sizes 2. Early termination for best-fit: Added smart exit condition when a "good enough" match is found - Exits early when perfect match found OR when chunk size ≤ requested size - Prevents unnecessary O(n) scanning of the entire freelist 3. Maintained hybrid allocation strategy: - First-fit for ≤40 bytes (fast allocation for small objects) - Best-fit for >40 bytes (memory-efficient allocation for large objects)
1 parent 3802292 commit 279f663

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

lib/c.c

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -647,8 +647,8 @@ void *malloc(int size)
647647
if (!__freelist_head->next) {
648648
allocated = NULL;
649649
} else {
650-
if (size <= 64) {
651-
/* First-fit for small allocations (speed optimization) */
650+
if (size <= 40) {
651+
/* First-fit for very small allocations */
652652
for (chunk_t *fh = __freelist_head; fh->next; fh = fh->next) {
653653
int fh_size = CHUNK_GET_SIZE(fh->size);
654654
if (fh_size >= size) {
@@ -658,15 +658,15 @@ void *malloc(int size)
658658
}
659659
}
660660
} else {
661-
/* Best-fit for large allocations (memory efficiency) */
661+
/* Best-fit for large allocations with early termination */
662662
for (chunk_t *fh = __freelist_head; fh->next; fh = fh->next) {
663663
int fh_size = CHUNK_GET_SIZE(fh->size);
664664
if (fh_size >= size &&
665665
(!best_fit_chunk || fh_size < best_size)) {
666666
best_fit_chunk = fh;
667667
best_size = fh_size;
668-
/* Early exit on perfect match to avoid useless scanning */
669-
if (best_size == size)
668+
/* Early exit on perfect match or very good match */
669+
if (best_size == size || best_size <= size + (size >> 3))
670670
break;
671671
}
672672
}

0 commit comments

Comments
 (0)