In this lesson, you will learn how to identify hidden heap allocations that force Unity to trigger garbage collection spikes, causing your game to stutter.
Understanding the Heap and Garbage Collection
In Unity, when you create objects or variables that are allocated on the "Managed Heap," the system reserves memory for them. When these objects are no longer needed, the Garbage Collector (GC) must scan through that memory to clean it up. If the GC has to do too much work at once, it freezes your game, resulting in a noticeable frame-rate spike.
Spotting Allocations in the Profiler
To monitor this, open the Profiler (Window > Analysis > Profiler) and ensure the Memory module is enabled.
- Switch to the CPU Usage Module: The GC activity actually shows up in the CPU timeline.
- Enable the "GC Alloc" Column: In the CPU module, switch the view from "Hierarchy" to "Timeline" or keep it in "Hierarchy." Look for the GC Alloc column.
- Search for Spikes: If you see a number greater than 0 bytes appearing in the
GC Alloccolumn every single frame, your code is creating temporary objects that will eventually trigger a garbage collection cleanup.
Common Culprits
A classic example of an "invisible" allocation that often goes unnoticed is string concatenation inside an Update() loop:
void Update() {
// This creates a new string object in the heap every single frame!
Debug.Log("Player Position: " + transform.position.ToString());
}
In the Profiler, you will see a small, repeating allocation in the GC Alloc column for this method. Even though it seems minor, doing this consistently throughout your game forces the Garbage Collector to work overtime, leading to those annoying micro-stutters. By monitoring the GC Alloc column, you can pinpoint exactly which lines of code are creating these "trash" objects and refactor them to use more memory-efficient approaches, such as caching strings or reusing objects.
Key Takeaway: Use the Profiler’s "GC Alloc" column to find code that creates temporary heap objects every frame, as these frequent allocations are the primary trigger for performance-draining Garbage Collection spikes.