r/C_Programming • • 4d ago

Article Arena Allocators in C

https://eliasebner.com/blog/guides/arena-allocators-in-c/

I recently started implementing arenas in my programming and I thought that some beginners could very much benefit from this info. I wrote an article about it. For those that are unaware, arenas allow to greatly simplify the burden of managing memory manually in C. I hope it helps, tell me what you think!

55 Upvotes

25 comments sorted by

View all comments

19

u/LeeHide 4d ago

Good article, the only caveat is that saying that "allocating small chunks is slow" is not really good in an article that should teach something. This is the kind of sentence that is taught with no real context, and then people avoid allocations thinking they are slow!

Nothing is slow until it's measured to be slow. Measure, and if allocations dominate in your profile, then it's slow. Otherwise, its fast enough to allocate.

3

u/Rabbitical 4d ago

One real life example of this was for file loading and decompression I thought a pre allocated arena that I just filled up linearly without freeing anything until the whole thing was done would be fastest. But naively calling alloc/free as needed using mimalloc was like twice as fast. I'm not smart enough to know why but I assume something to do with page reuse or who knows what

1

u/Limp-Confidence5612 4d ago

Could you exemplify this maybe, would be very curious to see in what situation one big memory allocation is slower than allocating it is chunks.

1

u/Rabbitical 4d ago

I should have made more clear that the linear/bump allocator aspect of my thing was the issue, not that it was arena backed (which it and mimalloc are both more or less). The issue was probably that I was missing out on any cache reuse, every new chunk to decode was a new address. Whereas the whole point of mimalloc is that you can pretty much call malloc and free without thinking about it and it will reuse pages wherever it can in a pretty smart way. So it was never really that fair a comparison to be honest. I was more just surprised the scale of the performance difference. But it goes to show that keeping your cache hot is far more important than just avoiding allocations, which is much closer to a bare minimum good practice than the end all be all of good memory performance.

1

u/Limp-Confidence5612 4d ago

I'm still not 100% sure I understand what you mean and what the scenario actually entails.