lunedì 7 dicembre 2015

Day 93: Double-stack allocator

Today I decided that I really don't like how I was going to handle memory yesterday. I left a few destructors, for example in the AudioManager or TextureManager classes, because they rely on libraries that allocate memory outside my control.

But for everything else I decided to use a double-stack allocator, instead of keeping a reference for each instanitated object. The idea is that a single chunk of memory is preallocated, and each new object is created on top of one of the two extremities of the chunk.

The resources used by the engine are pushed from the bottom, the resource of a scene from the top. When changing scene it is sufficient to reset the stack pointer to the top, while leaving the engine stack pointer where it is...

Pro:
- No mallocs, just one allocation
- Very easy to erase all the allocated objects without keeping references
- Easy to implement
- Neat division between temporary and persistent resources

Cons:
- It is a stack, so it is not possible to remove an allocated object if it is not on the top

Overall I think that the pros are quite interesting, because most resources are kept until the end of a scene. But I will also add a PoolAllocator and GeneralPurposeAllocator: the first will handle lots of identical objects, the second one will simply malloc those objects that really need to be deallocated sooner or later, and will keep pointers to those. It will be up to the developer which one to use in each case,  but I'll provide a simple interface.

Today I implemented the Double-Stack allocator.

Nessun commento:

Posta un commento