DOD — Unity Memory Best Practices — Part 2

Nitzan Wilnai
2 min readJun 6, 2024

Memory Fragmentation

Memory fragmentation is when we have holes in our heap memory. It is caused when we deallocate objects in a different order than how we allocated them.

Note that memory fragmentation is only a problem in the heap, not the stack, because in the stack data is automatically deallocated in the reverse order that it was allocated.

Let’s say we allocate 3 arrays, one 1KB, one 2KB and the third 1KB:

byte[] array1 = new byte[1024];
byte[] array2 = new byte[2048];
byte[] array3 = new byte[1024];

This is how they would look in memory:

If we delete array1 and array3, we’ll end up with holes:

Why is this bad?

In theory we have 2048KB of memory free, but each hole can only hold 1024KB worth of data. That means that if we try to allocate more than 1024KB our game will crash because we’ll be out of memory!

If we are constantly allocating and deallocating data on the heap, without being careful to do it in a Last In First Out order, our memory can quickly end up full of holes. Then once we try to allocate space for a big object our game will crash.

Part 3 — https://medium.com/@nitzanwilnai/dod-unity-memory-best-practices-part-3-f8e174f84bbb

--

--