TExcelTAD
Home › Unity with C# › GC Allocations

GC Allocations

Unity's C# runs with a garbage collector. Every new of a class, every string you build, every boxed value and every closure allocates managed memory. When enough garbage piles up, the GC pauses to collect it. Unity uses the incremental Boehm GC by default, which spreads work across frames, but a steady stream of garbage still costs CPU every frame and can still cause spikes. The cure is simple to state: allocate nothing per frame in steady-state gameplay.

The usual suspects

Allocates every call Allocation-free alternative
"Score: " + score /
quot;..."
every frame
update text only when the value changes; TMP_Text.SetText("Score: {0}", score)
GetComponents<T>() (array version), Physics.RaycastAll, OverlapSphere overloads that fill a reused List<T>, …NonAlloc versions with a cached array
new List<T>() inside Update a field you Clear() and reuse
LINQ (Where, Select, OrderBy) in hot paths plain for loops
lambdas that capture locals (() => target) cache the delegate in a field, or use non-capturing (static) lambdas
foreach over an interface (IEnumerable<T>) foreach over the concrete List<T>/array (struct enumerator)
boxing: object o = 5, string.Format("{0}", 5), enum as dictionary key in old runtimes generic APIs, typed collections
gameObject.tag, name, mesh.vertices CompareTag, cached names, mesh.GetVertices(list)
new WaitForSeconds(t) in a loop a cached instance or Awaitable.WaitForSecondsAsync
Instantiate/Destroy of bullets and effects object pooling

Find them with the Profiler's GC Alloc column (sort by it), then turn on Call Stacks for GC.Alloc samples to see the exact line.

Measuring allocations: a model

.NET can count the bytes the current thread allocated, which makes the difference easy to see. Each variant below runs the same "frame" 1,000 times:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var enemies = new List<Enemy>();
for (int i = 0; i < 100; i++) enemies.Add(new Enemy { Health = i % 7, Distance = i * 0.5f });

// warm up so first-call JIT costs don't count
Frames.Linq(enemies); Frames.Cached(enemies); Frames.StringEveryFrame(42); Frames.StringOnChange(42);

Measure("LINQ + new list per frame", () => Frames.Linq(enemies));
Measure("reused list, for loop    ", () => Frames.Cached(enemies));
Measure("string built every frame ", () => Frames.StringEveryFrame(42));
Measure("string only on change    ", () => Frames.StringOnChange(42));

static void Measure(string label, Action frame)
{
    long before = GC.GetAllocatedBytesForCurrentThread();
    for (int i = 0; i < 1000; i++) frame();
    long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
    Console.WriteLine(
quot;{label}: {bytes / 1000,6} bytes per frame"); } static class Frames { static readonly List<Enemy> nearbyBuffer = new(128); static string label = ""; static int shownScore = -1; public static int Linq(List<Enemy> all) { var nearby = all.Where(e => e.Distance < 20 && e.Health > 0).OrderBy(e => e.Distance).ToList(); return nearby.Count; } public static int Cached(List<Enemy> all) { nearbyBuffer.Clear(); for (int i = 0; i < all.Count; i++) { var e = all[i]; if (e.Distance < 20 && e.Health > 0) nearbyBuffer.Add(e); } return nearbyBuffer.Count; } public static void StringEveryFrame(int score) => label = "Score: " + score; public static void StringOnChange(int score) { if (score == shownScore) return; // nothing changed: no new string shownScore = score; label = "Score: " + score; } } class Enemy { public int Health; public float Distance; }
LINQ + new list per frame:   1224 bytes per frame
reused list, for loop    :      0 bytes per frame
string built every frame :     40 bytes per frame
string only on change    :      0 bytes per frame

The exact byte counts depend on the .NET version (Unity's runtime differs from the .NET 9 used here), but the shape doesn't: the cached version and the "only on change" version allocate zero bytes per frame in steady state.

Habits that keep Update clean

  1. Cache in Awake: components, Camera.main (cached by Unity in recent versions, but a field is still clearer), Shader.PropertyToID, Animator.StringToHash, WaitForSeconds.
  2. Pre-size collections (new List<T>(256)) so they don't grow during play.
  3. Use structs for small, short-lived data (but avoid boxing them through interfaces).
  4. Pool anything spawned repeatedly.
  5. Strings are for UI and logs. Wrap verbose logging in [System.Diagnostics.Conditional("ENABLE_LOGS")] helpers so it vanishes from release builds; Debug.Log is slow and allocates even when nobody reads the console.

Don't chase every byte in code that runs once per level load. The rule is about the per-frame steady state.

Test yourself

Which line allocates every frame when placed in Update?

  1. if (other.CompareTag("Enemy"))
  2. label.text = "HP: " + hp;
  3. hits = Physics.RaycastNonAlloc(ray, buffer);
  4. buffer.Clear();

Where do you find which code allocates managed memory each frame?

  1. The Console
  2. The Profiler's GC Alloc column (with call stacks enabled)
  3. The Frame Debugger
  4. The Lighting window

Why can a foreach over IEnumerable<T> allocate while a foreach over List<T> doesn't?

  1. Interfaces are slower to compile
  2. Through the interface the struct enumerator is boxed onto the heap
  3. List<T> has no enumerator
  4. foreach always allocates