Lesson 60 +10 XP

Memory Management & GC

Memory Management & GC

Unity uses the Mono or IL2CPP runtime for C# garbage collection. Understanding how memory is managed prevents gameplay stuttering.

Heap vs Stack

  • Stack: Stores value types (structs like Vector3, int, float, bool). Memory is managed automatically and instantly.
  • Heap: Stores reference types (classes like GameObjects, Monobehaviours, strings, arrays). Allocations are made dynamically.

Garbage Collection (GC)

When heap-allocated memory is no longer referenced, it becomes "garbage". The Garbage Collector (GC) scans the heap to free up this memory:

  • Scanning takes time.
  • If your game allocates a lot of temporary garbage in Update, the GC will run frequently.
  • This results in frame rate drops (micro-stuttering) during gameplay.

Avoiding GC Allocations

To keep your game running smoothly:

  • Avoid string concatenation in Update (use StringBuilder or format variables only when they change).
  • Use Object Pooling: Instead of calling Instantiate and Destroy repeatedly, keep a pool of inactive GameObjects and toggle them active/inactive.
  • Avoid temporary array allocations (e.g., use non-allocating physics APIs like Physics.RaycastNonAlloc instead of Physics.RaycastAll).

TL;DR

  • Stack allocations (structs) are fast; heap allocations (classes) generate garbage.
  • Garbage Collector sweeps trigger frame stutters.
  • Avoid string concatenations and temporary array instantiations inside Update.
  • Implement Object Pooling to reuse bullet and effect assets.