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










