Repository navigation
Faster heap creation and destruction, less purge churn - #59
Merged
Merged
Conversation
A block of statistics (`mi_stats_t`) has about 180 counts: one per statistic and one per size
bin for blocks, pages and chunks. `mi_stat_count_add_mt` added every count of the source into
the destination with an atomic add, also when the source count was all zero. That is one locked
instruction per count.
`mi_heap_delete` and `mi_heap_destroy` merge three times (theap into heap twice, heap into the
main heap), and almost all counts of a short-lived heap are zero. Since the sync with upstream
v3.5.2 the statistics are always on (`MI_STATS=1`) and a merge also walks the 74 `malloc_bins`:
it went from about 100 to about 180 locked adds.
A merge now returns early for a count whose total, peak and current value are all zero in the
source. A count with any value in it is merged as before.
`mi_heap_new` + n x `mi_heap_malloc` + `mi_heap_destroy` on one thread, x64 Linux, clang -O3,
per cycle (instructions counted by single-stepping, time is the minimum of 9 runs):
instructions locked instructions ns
n=0 before 5499 181 959
after 4508 11 314
n=1 (64 B) before 19332 591 3407
after 16471 93 1464
One difference: for an all-zero source the old code still raised the destination's peak to its
current value if the peak was lower. `mi_stat_update_mt` and `mi_stat_adjust_mt` return early
for a zero amount in the same way.
`test-stats-merge`: a merge adds up, a merge of an empty block does not write to a read-only
destination (this fails without the change), and the counts of destroyed heaps arrive in
`mi_stats_get`.
Per-heap work: - allocate heap statistics lazily (mi_heap_t: 6.5 KiB -> 2.1 KiB) - merge theap statistics once on release, non-atomically into the calling thread's theap of the main heap, skipping zero bins in groups - don't zero a theap before initializing it; don't copy zero statistics - generate the first chacha block of a split random context on demand - destroy pages that a detached theap still owns directly instead of abandoning and re-claiming them through the arena_pages bitmap - allocate arena_pages with a plain zalloc and align the bitmap inside - stop walking page queues once all pages are visited Locks and shared state: - shard the subprocess heap list by creating thread - publish arena_pages with a CAS and remove arena_pages_lock - take theaps_lock once on release; the detached list is private - skip os_abandoned_pages_lock for heaps without OS pages - keep the last freed thread-local key index and theap per thread, and reserve key versions in batches - count heaps/theaps in thread-local statistics - remove heap_count: all heaps use the thread's arena start index - move read-mostly subprocess fields off the contended cache lines Memory: - drop the cached theap reference on destroy - collect the meta-data theap when a thread exits
The page search unpurged a hole in the first page whose free list was empty, even if the blocks that were just freed sat resident in a page further down the queue. With a fragmented heap nearly every discard of the idle sweep was undone by the next request. - search without unpurging; a page with only purged blocks is a last resort before extending or allocating a fresh page - unpurge at most 8 KiB of a run at a time instead of the whole run - don't madvise an unformed tail that was never touched
A freed slice could stay resident until it was reused: - the purge bit was set after the check whether a pass is scheduled, so a pass in between left the bit set with nothing scheduled - the purge bit was set before the slice was marked free, so a pass in between cleared the bit, failed to claim the slice, and dropped it Mark the slices free, set the purge bits, and only then look at the expiration. The pass resets the expiration with an RMW so the reset is ordered before its scan. Most frees now skip the clock read and the CAS.
A pass purged every free slice, including slices that were freed a millisecond ago, and every idle sweep made all arenas due at once, so one thread going idle purged what busy threads had just freed. - keep two generations of purge bits: a free marks the young one; a pass purges the old one (skipping slices that were freed again since) and then swaps them. With a pass every delay/2, a slice is purged between delay/2 and delay after it was freed - remove _mi_arenas_purge_now. Without a scavenger an idle thread still purges everything at once as nobody would come back for it - when a range cannot be claimed as a whole, try each half instead of every slice: fewer madvise calls
Every mi_on_thread_idle_start issued a futex wake and a context switch to the scavenger, which usually found the thread not due for a sweep or already running again. At 158k parks/s it used 30% of a core. While threads keep parking the scavenger now looks at them by itself every purge_holes_min_interval, and a park only wakes it when it is not polling. It stops polling after an interval without parks. - remove parked_count (two shared RMWs per park) - don't issue a futex wake from the scavenger thread to itself
mi_malloc_aligned(64 KiB, 64 KiB) over-allocated a 128 KiB block in a large page (and 32 KiB took 64 KiB). JSC's MarkedBlocks are 64 KiB on Linux arm64. Pages start on a slice boundary so these can be aligned naturally, as was done for 16 KiB blocks before.
mi_heap_free freed the lazily allocated statistics before it took the heap out of its shard, so a walk over the heaps (mi_stats_get) could read them after the free. The thread local key is released after the unlink as well, which ends a race on heap->theap with the same walk. Sub-processes: - the fast key has no index: freeing the main heap of a sub-process made the thread keep index 1 for its next heap without claiming it, so two heaps could share a slot - mi_subproc_destroy released the thread locals of the calling thread also when that thread belongs to another sub-process, which then lost all its theaps - _mi_heap_theap_peek asserted on the main heap of another sub-process
With only purged blocks left every refill looked at 32 pages and moved them to the back, which made an allocation after an idle sweep 40-65% slower. After a search that finds no resident block the next ones look at 4 pages, until one of them finds a resident block again. - a resident block in a later page goes before extending the candidate - discard an untouched tail if transparent huge pages are allowed: it can be resident all the same
…urge With two alternating purge bitmaps a range whose slices were freed in between different passes was in neither of them as a whole, so with a minimal purge size it was never purged and the arena stayed scheduled forever. slices_purge is as it was again, and slices_purge_young has the slices that were freed since the last pass, which leaves those. - a pass that is an interval late purges everything: without a scavenger there may not be another one - a pass over all arenas also looks at an arena with purge bits where nothing is scheduled - the load and the CAS of the expiration are seq_cst - guarded builds: align the first block of a page naturally as well
…en idle Blocks that other threads free into the pages of a parked thread were not collected until that thread woke up. A thread that stays parked is now swept again every 30s, at the safety timeout of the scavenger. - a park that is not followed by another within two intervals means the process goes idle: purge the arenas right away instead of in two passes, and don't start polling - an idle thread of another sub-process purges by itself, and retries if another thread is in a pass - the park and the end of polling are ordered by seq_cst operations - don't purge arenas from a collect of the meta-data theap - count a freed theap where its statistics were merged into
The shorter search after one that found nothing made the requests after a sweep find the resident blocks late (or, for some block sizes, never all of them): the pages that have them are up to 16 pages apart. Always look past 32 pages again, and take back twice as much as the search before if that found nothing resident either (8 KiB up to 512 KiB). A burst of allocations after a sweep then searches once per page or so, which is what made it slow. 200 x 4 KiB per request: 28 faults (79 with the shorter search, 194 before). An allocation after a sweep that purged everything is 4-19% slower than before (40-65% with the long search for every 8 KiB). test-purge-resident: how many blocks stay resident depends on the block size and the build. Check that the requests end up taking none.
- the sweep of a thread that stays parked respects a purge_holes_min_interval of over 30s - schedule the pass for what a pass left from the end of that pass - mi_atomic_casi64_strong_seq_cst for the MSVC C atomics
Jarred-Sumner
added a commit
to oven-sh/bun
that referenced
this pull request
Oct 4, 2026
Jarred-Sumner
added a commit
to oven-sh/bun
that referenced
this pull request
Oct 4, 2026
…Bun.sleepSync (#44560) Bumps mimalloc to oven-sh/mimalloc#59. - mi_heap_new + mi_heap_destroy (every MimallocArena) is about 7x cheaper with one allocation and 13x cheaper when unused, and no longer slows down when several threads create heaps at once. - Purging stops doing work that is undone right away: an allocation takes resident memory before purged memory, purge_delay is a minimum age while threads are busy, and a park no longer wakes the scavenger every time. - Memory that other threads free into the pages of a thread that stays blocked is given back after 30 s instead of when that thread wakes up. - The event loop only hands its heaps to the scavenger on a poll that can block. - Bun.sleepSync hands them over as well, so what the thread freed does not stay resident for the whole sleep.
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two parts:
mi_heap_new/ first allocation /mi_heap_destroyget much cheaper, and no longer get slower with every extra thread. Includes the commit from stats: a merge skips a count that the source never touched #58.purge_delaybecomes a real minimum age, and a park no longer wakes the scavenger every time. No option default changes (purge_delayis still 100 ms).1. Heaps
Numbers
x64 Linux, clang, bun's release flags for
static.c. The process has a second thread (glibc elides thelockprefix on mutexes otherwise). One "heap" ismi_heap_new, n xmi_heap_malloc(64),mi_heap_destroy.Single thread:
3a13a5ffUser cycles per heap with T threads doing the same loop:
What is left of the n=1 growth is in the arena: threads take the lowest free slice, so they keep getting slices (and page meta-data) that another core touched last. I left that policy alone since it is what keeps memory compact.
20000 live heaps, RSS per heap: 6162 -> 2854 bytes unused, 32129 -> 28819 bytes with one block.
Stress test: T threads, each creates a heap, does up to N malloc/zalloc/aligned/realloc/free of 8 bytes to 1 MiB, checks the contents, then destroys it (10% are kept alive for a while, 10% are deleted instead). Median of 5 interleaved runs:
mi_collect(true)beforePeak RSS moves a few percent either way between runs. The small-heap rows at T=4/16 are about 1 MB higher at peak: the threads now actually run concurrently instead of queueing on a lock.
What changed
Less work per heap:
mi_heap_tgoes from 6.5 KiB to 2.1 KiB. A heap that is created, used and destroyed by one thread never needs them. Per-heap statistics of a live heap still work (mi_heap_stats_getetc.).mi_heap_destroyfrees the pages a detached theap still owns directly, instead of abandoning each one and claiming it back through thearena_pagesbitmap. Pages that were abandoned earlier still go through the claim protocol, andmi_heap_deleteis unchanged.arena_pagesno longer goes through the over-allocating aligned path.Less shared state:
arena_pages_lockis gone: entries are published with a CAS. This also removes the nested main-heap lock from the fork lock order.theaps_lockonce: after the detach the list is private.os_abandoned_pages_lockis skipped for heaps that never allocated a page from the OS._mi_theap_cachedused to keep the theap of the last destroyed heap alive; destroy now drops that reference.heapsandtheapsare counted in thread-local statistics.subproc->heap_countis removed. Its only use wasmi_arena_start_idx, which spread heaps over the arenas byheap_seq % heap_count. All heaps now start attseq % arena_cyclelike the main heap. No difference with up to two arenas.heap_main,theap_metaandprofilermoved to the front ofmi_subproc_t, away from the locks and counters.Memory:
Behaviour changes
heap_seqis still unique (0 for the main heap) but no longer in creation order.mi_subproc_visit_heapsvisits heaps in shard order.heaps/theapscounts of other threads show up inmi_stats_getwhen those threads merge, like every other theap-level count.2. Purging
Allocate from resident blocks before purged ones
The page search unpurged a hole in the first page whose free list was empty, even when the blocks that were just freed sat resident in a page further down the queue. With a fragmented heap nearly every discard of the idle sweep was undone by the next request, and then redone. The search now takes resident blocks first, then purged blocks, then extends a page. It looks past at most 32 pages that only have purged blocks. A hole is handed back 8 KiB at a time instead of as a whole run, and twice as much as the time before while the searches find nothing resident (up to 512 KiB), so a burst of allocations right after a sweep that purged everything does not search for every 8 KiB (it is 4-19% slower than before), and an unformed tail that was never touched is not madvised (unless THP is allowed).
64 MiB heap of which 1/8 is live, each "request" mallocs and frees K blocks and then parks for 10 ms:
purge_delayis a minimum ageOnly the first free into an arena started the timer, so a pass also purged slices that were freed a millisecond ago. And every idle sweep made all arenas due at once (
_mi_arenas_purge_now), so one thread going idle purged what busy threads had just freed.slices_purge_younghas the slices that were freed since the last pass. A free sets its bit there and inslices_purge; a pass leaves the slices that are young, and clearsslices_purge_youngat its end. With a pass everydelay/2a slice is purged betweendelay/2anddelayafter it was freed. A pass that is an interval late purges everything (without a scavenger there may not be another one)._mi_arenas_purge_nowis removed. Instead the scavenger tells a thread that goes idle from threads that park all the time: a park that no other park follows within two intervals (200 ms) is followed by a forced purge, as before. So a process that goes idle reaches its lowest RSS as fast as it did, with the same number of scavenger wake-ups.Allocate and touch 16 x 1 MiB, hold, free, wait, repeat. Minor faults per cycle (4096 = everything was purged and faulted back in):
Lost purges
A freed slice could stay resident until it was reused: the purge bit was set after the check whether a pass is scheduled (a pass in between left the bit set with nothing scheduled), and before the slice was marked free (a pass in between cleared the bit, failed to claim the slice, and dropped it). The order is now: mark free, set the bit, look at the expiration; the pass resets the expiration with an RMW. Most frees now skip the clock read and the CAS. When a range cannot be claimed as a whole the pass tries each half instead of every slice.
The scavenger polls while threads keep parking
Every
mi_on_thread_idle_startissued a futex wake and a context switch to the scavenger, which usually found the thread not due or already running again. While threads keep parking the scavenger now looks at them by itself everypurge_holes_min_interval, and a park only wakes it when it is not polling. It only starts to poll when parks follow each other within 200 ms, and stops after an interval without parks. This replacesparked_count(two shared RMWs per park). This overlaps with #56/#57.20000 parks of 50 us: 39932 futex calls before, 43 after. A process that is idle for 65 s: 10 futex and 20 madvise calls before, 12 and 8 after. A 2 Hz timer: 1.0 scavenger wake-ups per tick before and after.
A thread that stays parked is swept again
Blocks that other threads free into the (not full) pages of a parked thread sit on
xthread_freeuntil the owner collects them, and a park was swept once. 200 MiB of 256 B blocks, the owner parks, another thread frees them all: RSS stayed at 214 MiB until the owner woke up. Now the scavenger sweeps a thread that stays parked again every 30 s, at its safety timeout, so there are no extra wake-ups: 9 MiB after 30 s. A sweep that finds nothing takes 0.03 ms here.Smaller things
mi_malloc_aligned(64 KiB, 64 KiB)took a 128 KiB block in a large page (and 32 KiB took 64 KiB). Power-of-two blocks up to the slice size are now aligned naturally, as 28264ca did for 16 KiB. JSC's MarkedBlocks are 64 KiB on Linux arm64. The number of blocks per page does not change.mi_subproc_destroyreleased the thread locals of the calling thread also when it belongs to another sub-process: it lost its theaps, got a second main theap, and a debug build asserted. Also on3a13a5ff.3a13a5ffwithMIMALLOC_DISALLOW_ARENA_ALLOC=1).test-park-handoff-eager(the test sets an option while the scavenger reads it).Tests
test/test-heap-new.c: statistics of live and destroyed heaps, visiting heaps across shards, key reuse against stale theaps in other threads, release of meta-data pages, and the stress test above in small. Each part fails when the matching code is broken on purpose.New tests, each of which fails without the change it is for:
test-purge-resident(the requests end up taking no purged blocks; about 67 runs per request before),test-purge-age(minimum age, a late pass, a minimal purge size),test-park-again, and intest-heap-newa walk over the heaps while they are destroyed (needs ASAN or TSAN to fail) and heaps after ami_subproc_destroy.Changed tests:
test-purge-behind-passreads the statistics of its heap before it starts counting purged bytes (they are allocated lazily now, and that took a slice it counts on);test-fork-user-heaponly has comments updated.Passes locally: debug (
MI_DEBUG=FULL) and release as C and C++,MI_SECURE=ON, TSAN, ASAN, UBSAN.CI
The 32-bit Windows configurations are removed.
test-stress-subprocswent from 22 s to over 240 s there (64-bit is unchanged: 22.2 s vs 22.7 s). Thread stacks of a slow run show no lock or spin: 20 of the 32 workers are inMEM_RESET/VirtualUnlockundermi_on_thread_idle, which the test calls on 1% of its operations.