3 Memory allocations and performance
This chapter covers
- Memory Fragmentation.
- Avoiding garbage collector related slowdowns.
- Avoiding fragmented memory and garbage collection with object pools.
- Ideal Memory Allocations.
As game developers, we want our games to be performant and run at a high frame rate so users have a smooth, enjoyable experience. Bad memory management can hurt the user experience by causing sudden performance drops and even crashes. In this chapter, we’ll explore when to allocate and deallocate data to minimize garbage-collector triggers, which can hurt performance. We’ll also look at how we can avoid memory fragmentation, which can lead to unexpected out-of-memory crashes. We’ll also look at popular memory management solutions like object pools and how to implement them in DOD to maximize our performance.
3.1 Memory fragmentation
Memory fragmentation occurs when we have holes in our heap memory, as seen in Figure 3.1.
Figure 3.1 An example of fragmented heap memory, with holes of unused memory surrounded by allocated memory.
Heap memory can become fragmented when we deallocate objects in a different order than we allocated them. The memory manager stores heap-allocated objects in one big chunk. The memory manager is not designed to break them up into multiple pieces. If we try to allocate an object too big for any available memory holes, our game will crash, even though all the memory holes added together are big enough.