liveBook · Manning

Memory fragmentation

As explained in High Performance Unity Game Development

Memory fragmentation is the condition in which available memory is divided into separated holes that may not accommodate a requested contiguous allocation.

In a Unity survival game, repeatedly instantiating enemies and destroying them after they are shot can leave gaps in heap memory. Those gaps matter when a later allocation needs one contiguous chunk, not merely enough free memory in total. section 3.3 section 3.3.1 section 3.1

Enough free memory, but no room

Allocate arrays of 1 KB, 2 KB, and 1 KB, then remove the first and third. The two resulting holes total 2 KB, but each holds only 1 KB. A new 1.5 KB array cannot fit in either hole. section 3.1

Figure 3.4 We have 2048 bytes of memory free, but if we try to allocate an array of 1536 bytes, we’ll run out of memory because the biggest contiguous space is 1024 bytes.

The diagram contrasts total free space with the largest contiguous hole—the limit that determines whether the new array fits. section 3.1

Heap objects can leave separated holes when they are released in a different order from their allocation. Stack data avoids this pattern by being released in reverse order. Unity adds a constraint: destroying a GameObject does not make its memory immediately reusable, and its garbage collector does not compact the remaining objects to close gaps. section 3.1 section 3.3.1 section 3.2

Reduce the churn that creates holes:

  • Keep related heap data with the same lifetime together; release it together or in reverse order where possible. section 3.1
  • For frequently spawned enemies, reuse GameObjects from an object pool rather than repeatedly instantiating and destroying them. section 3.3.1 section 3.6
  • Allocate common data when the game loads and level-specific data when the level loads; avoid routine allocation and deallocation during gameplay. section 3.6

How High Performance Unity Game Development covers it

How deep it goes
Works through contiguous-allocation failure with three arrays and explains Unity’s delayed reclamation and non-compacting garbage collector.
Examples
Uses three arrays with two 1 KB holes, plus repeatedly instantiated and destroyed enemy GameObjects.
What it assumes
Assumes familiarity with C# arrays and Unity GameObjects while explaining heap holes through a small allocation example.
What you can do after
Practice/perform it by grouping heap data by lifetime and reusing pooled GameObjects to limit gameplay allocation churn.
How it connects
Connects heap allocation and stack-order release to garbage collection, object pools, and allocation lifetime.

Also explained in

Compare how 3 books explain memory fragmentation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.