Releasing vmem, reloaded

^ Up

2026 August

Here's a cool strategy I came up with that's a huge improvement over the naive one with the array sort explained here:

At least, it doesn't require extra memory allocation, so it would be safe to use whenever. All it needs is a statically allocated array, like in the .data or .bss section of the executable.

As above, I will describe the algo in terms of a single size class; just loop over the size classes and apply it to as many as needed until enough memory is released to the kernel.

OK, a small improvement immediately occurs to me:

Choosing a sufficiently large static array could actually make this quite effective, but 16 or 32 probably won't cut it. It all depends on the user's memory allocation and freeing patterns, but using an array of length 1024 or a small multiple thereof may work well.

Ultimately, it's better than nothing. The size of the array sets a lower bound on the length of the span we will find in the pessimal case: N * slot_size. For N = 1024, and the smallest size class, which is 128 bytes, that's still... 128 KiB. OK, maybe that's not very much, but it's the absolute worst case.

(Later addition: Nope, it's even worse, because we may end up having to skip lots of indexes, when the array is full, that would have at some point revealed that it's one big span. The real worst-case is something much worse I think, but it doesn't matter anymore because read on...)

Another improvement comes to mind, along with a flaw in the original plan:

First of all, the static array must be large enough to hold at least every element of a free-list node including the head of the chunk. And that twice, since each index is stored as FROM and TO initially. Given 16-element chunks, that means the array must be at least 34 indexes long. The reason is simple: I didn't consider at what point entries / chunks would be pruned from the free-list. If every index of a chunk is inserted into our array, OK, detach the chunk, but if there's even one index that remains unhandled, what do we do with it? The chunk header has to stay in the free-list, the other indexes get "liberated" from it, and the one index we couldn't handle remains. That's pretty ugly.

But lo and behold: What if we reuse the memory of the free slots?? Even with the smallest size class of 128, that's space for 32 more index values.

We could build a B-tree of free slots, out of the free slots!

I'm getting tired, so I think I'll leave it here.

To be continued...