[PATCH 2/3] malloc: Only fill half of the tcache during batch allocation
Florian Weimer
fweimer@redhat.com
Thu Dec 18 10:17:52 GMT 2025
This leaves room for subsequent frees.
---
malloc/malloc.c | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/malloc/malloc.c b/malloc/malloc.c
index d2184c8d7a..d42f0183e3 100644
--- a/malloc/malloc.c
+++ b/malloc/malloc.c
@@ -3940,8 +3940,11 @@ _int_malloc (mstate av, size_t bytes)
if (__glibc_unlikely (tcache_inactive ()))
tcache_init (av);
- /* While bin not empty and tcache not full, copy chunks over. */
- while (tcache->num_slots[tc_idx] != 0
+ /* While bin not empty and tcache not full, copy chunks over.
+ Only fill half of the tcache, so that subsequent frees
+ do not immediately flush the tcache. */
+ unsigned int tcache_target_count = mp_.tcache_count / 2;
+ while (tcache->num_slots[tc_idx] > tcache_target_count
&& (tc_victim = last (bin)) != bin)
{
if (tc_victim != NULL)
@@ -3988,6 +3991,7 @@ _int_malloc (mstate av, size_t bytes)
if (tc_idx < mp_.tcache_small_bins)
tcache_nb = nb;
int return_cached = 0;
+ unsigned int tcache_target_count = mp_.tcache_count / 2;
tcache_unsorted_count = 0;
#endif
@@ -4066,9 +4070,11 @@ _int_malloc (mstate av, size_t bytes)
if (__glibc_unlikely (tcache_inactive ()))
tcache_init (av);
/* Fill cache first, return to user only if cache fills.
- We may return one of these chunks later. */
+ We may return one of these chunks later. Only fill
+ half of tcache, so that subsequent frees do not flush
+ it immediately. */
if (tcache_nb > 0
- && tcache->num_slots[tc_idx] != 0)
+ && tcache->num_slots[tc_idx] > tcache_target_count)
{
tcache_put (victim, tc_idx);
return_cached = 1;
--
2.52.0
More information about the Libc-alpha
mailing list