3 ms·
Zig is general purpose and isn't really focused on embedded as much as it's focused on being flexible enough to also support embedded development. Configurable
by nyberg 5y ago
Zig is general purpose and isn't really focused on embedded as much as it's focused on being flexible enough to also support embedded development.
Configurable allocators are present in other languages (iirc rust allows it at the crate level, in C++ https://en.cppreference.com/w/cpp/memory/allocator https://en.cppreference.com/w/cpp/memory/allocator) but in zig the style makes allocating functions explicit which is nice even for regular application development. It's a bit like Haskell being explicit about side-effects (IO Monad, Eff, etc). Also, passing the allocator in zig is just a convention and not enforced by the compiler so you could use `std.heap.page_allocator` or any other global allocator anywhere in your code without passing it in but then your code is less flexible.
Now for the use of the, imagine you need to serve a HTTP request; you pass an ArenaAllocator to the request handler which can allocate memory by need and without a need for calling free() for small objects. Once the handler has generated a response, the caller can free up all of the allocated memory in one step rather than having small deallocations all over for memory that will only have a life-time for the duration of the request. The handler itself doesn't need to know that it's being used this way and can be written to call free in the usual manner to be compatible with other allocators (free() with ArenaAllocator is a "nop").
Imagine you have a game, there you'll likely allocate a huge chunk at the start for all of your resources then use your own custom allocators within to both isolate systems from one another along with allowing different strategies based on your usecase. You might not always know which compiler will be best but since it's a parameter you can easily test or even decide at runtime on the strategy to use.