Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

IMHO trying to emulate smart pointers in C is fixing a problem that shouldn't exist in the first place, and is also a problem in C++ code that uses smart pointers for memory management of individual objects.

Objects often come in batches of the same type and similar maximum lifetime, so let's make use of that.

Instead of tracking the individual lifetimes of thousands of objects it is often possible to group thousands of objects into just a handful of lifetime buckets.

Then use one arena allocator per lifetime bucket, and at the end of the 'bucket lifetime' discard the entire arena with all items in it (which of course assumes that there are no destructors to be called).

And suddenly you reduced a tricky problem (manually keeping track of thousands of lifetimes) to a trivial problem (manually keeping track of only a handful lifetimes).

And for the doubters: Zig demonstrates quite nicely that this approach works well also for big code bases, at least when the stdlib is built around that idea.



This is the way


It makes the code so much simpler. And quite probably faster as there's less malloc/free churn.

A lot of problems break down to:

* we need this effectively forever (i.e. until config reload)

* we need this very briefly when processing a task or request

Sometimes you need a cache that has intermediate lifetimes, but that is a much smaller problem to deal with, and you can often cope with manual memory management for that

Hook any file handles and other resource cleanup functions into the same pools and you have a pretty easy life.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: