liveBook · Manning

Heap

As explained in High Performance Unity Game Development

A region of runtime memory used for dynamically allocated data whose lifetime is managed separately from function call frames.

A survival game needs enemy data to remain available across frames. The heap holds long-lived and dynamically allocated data, including C# class instances, arrays, and strings. Unlike temporary stack data, heap data can outlive the function call that created it. section 2.2.2 section 2.7

Listing 2.5 C# class holding all the data for all enemies
public class EnemyData
{
    public Vector2[] Position;
    public Vector2[] Direction;
    public float[] Velocity;
}

The enemy-data class holds separate arrays for position, direction, and velocity. The class and its dynamically allocated arrays use heap memory; arranging frequently processed values in arrays helps make access more local. section 2.2.2 section 2.0

Heap allocations go wherever space is available, so separate objects may be far apart and cause cache misses. An array of structs keeps its elements in one contiguous block; an array of classes instead holds references to objects that may be scattered. Choose a layout for the data the game actually processes together. section 2.2.2 section 2.8

A string inside a struct

Putting a Name string in an enemy struct does not put the string’s contents alongside the struct’s other fields. Assigning a new name allocates a new string on the heap; the old string’s memory cannot be reused until garbage collection frees it. section 2.4.3

Allocation frequency matters as well as layout. In Unity, destroying an enemy GameObject does not make its heap memory immediately reusable. Repeated allocation can scatter objects and contribute to fragmentation; the managed heap is not compacted. Avoid unnecessary per-frame allocations, and check the effect with the Unity Profiler rather than assuming every heap allocation needs removal. section 3.2.1 section 2.2.2

How High Performance Unity Game Development covers it

How deep it goes
Explains allocation placement, locality, and delayed reuse with examples, while deferring fuller garbage-collection and fragmentation treatment.
Examples
Uses enemy-data arrays, a string-bearing struct, destroyed GameObjects, and temporary arrays inspected in the Unity Profiler.
What it assumes
Assumes familiarity with C# classes, structs, arrays, and Unity gameplay data; introduces the stack–heap distinction.
What you can do after
Evaluate/understand heap-related locality and allocation costs when choosing C# data layouts for Unity gameplay.
How it connects
Connects heap allocation to the stack, arrays, structs, classes, data locality, cache misses, and garbage collection.

Also explained in

Compare how 11 books explain heap →

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.