- Hands-On High Performance Programming with Qt 5
- Marek Krajewski
- 270字
- 2021-07-02 13:54:00
Where they do make sense
In game programming, custom allocators are widely used because of very specific requirements, as they are constantly creating objects at runtime, such as meshes, sprites, textures, and so on. In this regard, the following allocator types are used:
- Single-frame memory: This contains memory for operations that occur within one frame cycle. After the frame is rendered, we don't have to deallocate all memory, but we just reset the pointer in the memory buffer of our allocator (ideally without running destructors of any contained object!). This is also called an arena in standard contexts.
- Object pools: Also called fixed size allocators, they contain many same-sized objects (particles, projectiles, spaceships), and hence they simplify the allocation logic extremely. Additionally, they cater for good memory locality. You would like to have all of your particles in a nice array, wouldn't you?
Another example where a custom memory manager could make sense is for the serialization and deserialization of objects for network transmission. If we have complex objects containing dynamic sub-objects (remember a string object will be dynamic!), the dynamic allocation costs can be heavy. We could optimize network communication by using a custom allocator for message serialization on a per-message basis. As an example, Google's Protocol Buffers offer a protobuf::Arena class, which can be used as a custom allocator for serialization.
Yet another possible scenario would be using an allocator to assure that all objects of a given type are stored in a contiguous sequence, thus improving the memory locality of some inefficient data structure (think of a list and its nodes) in a refactoring step.