Skip to content
ToanLB
Go back

No 'new' Keyword in Code, Yet Profiler Reports GC Alloc: Dissecting 4 Hidden Allocation Traps in Unity

~13 min read
No 'new' Keyword in Code, Yet Profiler Reports GC Alloc: Dissecting 4 Hidden Allocation Traps in Unity

When developing high-performance Unity games targeting a steady 60 FPS on mobile hardware, many developers rely on a comforting intuition: “Code only allocates memory on the Managed Heap when explicitly invoking the new keyword”.

However, during real-world device profiling sessions under combat or open-world navigation, the Unity Profiler frequently tells a conflicting story: the GC Alloc column under Update.ScriptRunBehaviourUpdate persistently ticks upward by 20 KB to 40 KB every single frame. Searching the entire combat codebase for the new keyword yields zero hits!

This disconnect occurs because the Roslyn C# compiler and the .NET Common Language Runtime (CLR) implicitly emit allocation instructions on the Managed Heap behind seemingly benign language features. Four notorious anti-patterns account for roughly 90% of these recurring GC Spikes: Boxing, Closures, LINQ in the game loop, and String immutability.


1. Classification of the 4 Hidden Allocation Traps in the Game Loop

Understanding how each mechanism triggers heap memory allocation allows engineering teams to diagnose and optimize hot paths effectively:

flowchart LR
    B1["<b>1. Boxing Allocation</b><br/>• Value type cast to object/interface<br/>• Heap wrapper object allocated<br/>• Solution: Generic constraints"]
    B2["<b>2. Lambda Closures</b><br/>• Capturing outer scope or this<br/>• Generates DisplayClass on Heap<br/>• Solution: Index loops / Static"]
    B3["<b>3. LINQ in Loops</b><br/>• Iterator state machine objects<br/>• Struct Enumerator boxed to interface<br/>• Solution: For loops & Buffers"]
    B4["<b>4. String Immutability</b><br/>• + operator invokes string.Concat<br/>• .tag getter allocates native copy<br/>• Solution: SetText & CompareTag"]

    B1 --> B2 --> B3 --> B4

2. Technical Dissection: Engine Internals and CLR Mechanics

2.1. Boxing: When Value Types Transform into Reference Types

In the .NET runtime architecture, Value Types (primitives like int, float, bool, and struct) are allocated directly on the CPU execution stack or embedded inline within their containing heap object.

However, when a Value Type is assigned to an object reference, cast to System.ValueType, or passed into an interface parameter, the CLR executes Boxing:

  1. It allocates a new memory block on the Managed Heap sized to the struct payload plus object overhead (Method Table Pointer and Sync Block Index, typically 16 bytes on 64-bit architectures).
  2. It performs a byte-for-byte copy of the struct data from the Stack into the newly allocated Heap payload.
  3. It returns a reference pointer pointing to the boxed object on the Heap.

Common Boxing Pitfalls in Production:

Important

Silent Mutation Logic Bug on Boxed Structs: Boxing a struct does not merely waste memory; it frequently introduces critical silent logic errors. When casting a struct to an interface, the CLR generates an independent heap-allocated clone. Invoking damageable.ApplyDamage(payload.Amount) mutates only that transient heap replica. The original struct in your array or collection retains its initial health! Consequently, targets appear invulnerable despite clean compilation with zero warnings.


2.2. Closures: The Hidden State Machines Behind Lambdas

Lambda expressions (() => { ... }) provide clean, functional syntax. However, they become constant garbage generators when developers overlook Roslyn’s closure generation rules.

Non-Capturing vs. Capturing Lambdas:

Elimination Strategy:

In high-frequency loops, avoid capturing lambdas entirely. Replace queries with standard indexed for loops or pass state via struct-based context parameters.


2.3. LINQ in the Game Loop: Convenience at High Cost

LINQ (Language Integrated Query) is an exceptional tool for Editor scripting, build pipelines, and initial scene configuration. In high-frequency game loops (Update, FixedUpdate, combat evaluation), however, LINQ is a primary cause of micro-stuttering and GC Spikes.

Executing a standard chained query in Update such as var enemies = allTargets.Where(t => t.IsAlive).OrderBy(t => t.Distance).Take(3).ToList(); triggers a succession of hidden heap allocations:

  1. Where() allocates an iterator state machine object (WhereEnumerableIterator<T>) on the Heap.
  2. Allocates a delegate instance for the predicate t => t.IsAlive.
  3. OrderBy() allocates an ordering helper object (OrderedEnumerable<T>) along with internal sort buffers.
  4. Casting to IEnumerable<T> causes foreach enumeration to box the high-performance struct enumerator of List<T> (List<T>.Enumerator) into an IEnumerator<T> interface instance.
  5. ToList() instantiates an entirely new List<T> object on the Managed Heap.

Elimination Strategy:

Replace chained LINQ expressions in hot paths with index-based for loops using pre-allocated buffers and in-place sorting routines (such as Insertion Sort for small collections under 32 elements).


2.4. String Immutability and the Native Engine Binding Trap

System.String in C# is an immutable reference type. Every operation utilizing the + operator, int.ToString(), or string.Replace() produces a new string instance on the Managed Heap.

Two Classic String Pitfalls in Unity:

  1. Real-time UI Text Updates: Code like uiText.text = "Score: " + score; translates to string.Concat(string, object). This operation simultaneously boxes score into an object and allocates a new string on the Heap every frame.
  2. Tag Comparisons via gameObject.tag == "Boss": The property getter gameObject.tag transitions across the native C++ engine boundary. To return data to managed C#, the engine allocates a brand-new managed C# string on the Heap and copies the character bytes. This overhead applies to many native engine getters (gameObject.name, transform.name, legacy Input.touches). Conversely, invoking: gameObject.CompareTag("Boss") passes the managed string reference down into native C++, performing an internal hash comparison at native speed with 0 bytes GC Alloc.

3. Practical C# Implementation: Naive Code vs. Zero-Alloc Refactoring

To observe the concrete architectural differences between convenient prototyping habits and production-grade zero-allocation code, consider an Action RPG combat scenario on mobile hardware: an arena containing 50 to 100 active combatants. Every frame in Update(), combat targeting routines must continuously identify living targets within range, classify entities at critical health thresholds, and dispatch damage.

Under a strict 60 FPS frame budget (16.6 milliseconds total for rendering, physics, and scripting), the managed memory budget for this combat loop must strictly remain at 0 bytes GC Alloc to prevent periodic Garbage Collection stalls.

First, the core data contracts and types:

using System;

public interface IDamageable
{
    int CurrentHp { get; }
    void ApplyDamage(int amount);
}

public readonly struct DamagePayload
{
    public int Amount { get; }
    public int SourceId { get; }

    public DamagePayload(int amount, int sourceId)
    {
        Amount = amount;
        SourceId = sourceId;
    }
}

public struct CombatTargetData : IDamageable
{
    public int Id;
    public int CurrentHp { get; set; }
    public float Distance;
    public bool IsAlive => CurrentHp > 0;

    public CombatTargetData(int id, int hp, float distance)
    {
        Id = id;
        CurrentHp = hp;
        Distance = distance;
    }

    public void ApplyDamage(int amount)
    {
        CurrentHp = Math.Max(0, CurrentHp - amount);
    }
}

3.1. Naive Implementation: 4 Hidden Garbage Traps Executing in Update

The following implementation appears compact and contains no explicit new statements in its methods, yet it allocates dozens of kilobytes every second:

using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class NaiveCombatProcessor : MonoBehaviour
{
    [SerializeField] private float combatRadius = 20f;
    [SerializeField] private int minHpFilter = 50;
    private readonly List<CombatTargetData> _targets = new();

    public string CombatStatusReport { get; private set; }

    private void Update()
    {
        ExecuteCombatCycle(combatRadius, minHpFilter);
    }

    public void ExecuteCombatCycle(float maxRadius, int hpThreshold)
    {
        // Trap 1: Boxing when passing struct to interface without generic constraints
        for (int i = 0; i < _targets.Count; i++)
        {
            var target = _targets[i];
            DamageTargetViaInterface(target, new DamagePayload(25, 999));
        }

        // Trap 2: Lambda Closure - capturing 'hpThreshold' creates DisplayClass on Heap
        var criticalTarget = _targets.Find(t => t.CurrentHp <= hpThreshold);

        // Trap 3: LINQ in Game Loop - allocates Iterators, Delegates, and boxes Enumerator
        var priorityEnemies = _targets
            .Where(t => t.IsAlive)
            .OrderBy(t => t.Distance)
            .Take(3)
            .ToList();

        // Trap 4: String Immutability and string.Concat allocate new strings each frame
        CombatStatusReport = "Active: " + priorityEnemies.Count + " | Critical: " + criticalTarget.Id;
    }

    private void DamageTargetViaInterface(IDamageable damageable, DamagePayload payload)
    {
        // Casting struct to interface IDamageable boxes it onto the Managed Heap
        // and mutates only the transient heap clone
        damageable.ApplyDamage(payload.Amount);
    }
}

3.2. Refactoring: Zero-Alloc Architecture

To eliminate these allocations, we refactor the combat processor according to production standards:

using System.Collections.Generic;

public class ZeroAllocCombatProcessor
{
    private readonly CombatTargetData[] _queryBuffer;
    private int _lastProcessedCount;

    public int LastProcessedCount => _lastProcessedCount;

    public ZeroAllocCombatProcessor(int maxCapacity = 32)
    {
        _queryBuffer = new CombatTargetData[maxCapacity];
    }

    // Resolves Trap 1 (Boxing): Generic constraint emits 'constrained. callvirt'
    public void DamageTargetNonAlloc<T>(ref T target, in DamagePayload payload) where T : struct, IDamageable
    {
        target.ApplyDamage(payload.Amount);
    }

    // Convenience overload utilizing the internal pre-allocated buffer
    public int FilterAndSelectTopTargetsNonAlloc(
        IReadOnlyList<CombatTargetData> pool,
        float maxDistance,
        int hpThreshold,
        out int criticalTargetId)
    {
        return FilterAndSelectTopTargetsNonAlloc(pool, _queryBuffer, maxDistance, hpThreshold, out criticalTargetId);
    }

    // Resolves Traps 2 & 3 (Closures & LINQ):
    // Replaces LINQ and capturing lambdas with index loops over pre-allocated buffers
    public int FilterAndSelectTopTargetsNonAlloc(
        IReadOnlyList<CombatTargetData> pool,
        CombatTargetData[] outputBuffer,
        float maxDistance,
        int hpThreshold,
        out int criticalTargetId)
    {
        criticalTargetId = -1;
        if (pool == null || outputBuffer == null || outputBuffer.Length == 0)
        {
            return 0;
        }

        int matchCount = 0;
        int capacity = outputBuffer.Length;

        for (int i = 0; i < pool.Count; i++)
        {
            var target = pool[i];

            // Identifies critical targets without closure allocations
            if (criticalTargetId == -1 && target.CurrentHp <= hpThreshold)
            {
                criticalTargetId = target.Id;
            }

            // Filters active targets within range without iterator state machines
            if (target.IsAlive && target.Distance <= maxDistance)
            {
                outputBuffer[matchCount] = target;
                matchCount++;

                if (matchCount >= capacity)
                {
                    break;
                }
            }
        }

        // In-place distance sort over the output buffer without OrderBy allocations
        SortBufferByDistanceNonAlloc(outputBuffer, matchCount);

        _lastProcessedCount = matchCount;
        return matchCount;
    }

    private static void SortBufferByDistanceNonAlloc(CombatTargetData[] buffer, int count)
    {
        // Insertion sort optimal for small arrays (N < 32) with 0 bytes GC Alloc
        for (int i = 1; i < count; i++)
        {
            var key = buffer[i];
            int j = i - 1;
            while (j >= 0 && buffer[j].Distance > key.Distance)
            {
                buffer[j + 1] = buffer[j];
                j--;
            }
            buffer[j + 1] = key;
        }
    }
}

3.3. Verification via NUnit Unit Tests: Logic, Clamping, and Zero GC Alloc Assertion

To verify algorithmic correctness, array bounds protection, and strictly zero bytes of heap allocation, the automated test fixture HiddenAllocBenchmarkTests is structured as follows:

using System;
using System.Collections.Generic;
using NUnit.Framework;

[TestFixture]
public class HiddenAllocBenchmarkTests
{
    [Test]
    public void DamageTargetNonAlloc_WithStruct_ModifiesHpWithoutBoxing()
    {
        var processor = new ZeroAllocCombatProcessor();
        var target = new CombatTargetData(1, 100, 10f);
        var payload = new DamagePayload(35, 999);

        processor.DamageTargetNonAlloc(ref target, in payload);

        Assert.AreEqual(65, target.CurrentHp);
    }

    [Test]
    public void DamageTargetNonAlloc_AllocatesZeroBytesOnManagedHeap()
    {
        var processor = new ZeroAllocCombatProcessor();
        var target = new CombatTargetData(1, 100, 10f);
        var payload = new DamagePayload(20, 101);

        // JIT warm-up
        processor.DamageTargetNonAlloc(ref target, in payload);

        long beforeAlloc = GC.GetAllocatedBytesForCurrentThread();
        processor.DamageTargetNonAlloc(ref target, in payload);
        long afterAlloc = GC.GetAllocatedBytesForCurrentThread();

        Assert.AreEqual(60, target.CurrentHp);
        Assert.AreEqual(0, afterAlloc - beforeAlloc, "DamageTargetNonAlloc with generic constraint must strictly allocate zero bytes on the Managed Heap!");
    }

    [Test]
    public void FilterAndSelectTopTargetsNonAlloc_InternalBufferOverload_WorksCorrectly()
    {
        var processor = new ZeroAllocCombatProcessor(8);
        var pool = new List<CombatTargetData>
        {
            new(1, 50, 5f),
            new(2, 80, 12f)
        };

        int count = processor.FilterAndSelectTopTargetsNonAlloc(pool, 10f, 60, out int critId);

        Assert.AreEqual(1, count);
        Assert.AreEqual(1, critId);
        Assert.AreEqual(1, processor.LastProcessedCount);
    }

    [Test]
    public void FilterAndSelectTopTargetsNonAlloc_SortsByDistanceAndFindsCritical()
    {
        var processor = new ZeroAllocCombatProcessor();
        var pool = new List<CombatTargetData>
        {
            new(101, 80, 25f), // Furthest
            new(102, 10, 5f),  // Closest and below critical HP
            new(103, 0, 8f),   // Dead, skipped
            new(104, 60, 12f)  // Middle
        };

        var buffer = new CombatTargetData[4];
        int count = processor.FilterAndSelectTopTargetsNonAlloc(pool, buffer, 30f, 20, out int criticalId);

        Assert.AreEqual(3, count);
        Assert.AreEqual(102, criticalId);
        // Validates ascending distance sort order (5f -> 12f -> 25f)
        Assert.AreEqual(102, buffer[0].Id);
        Assert.AreEqual(104, buffer[1].Id);
        Assert.AreEqual(101, buffer[2].Id);
    }

    [Test]
    public void FilterAndSelectTopTargetsNonAlloc_AllocatesZeroBytesOnManagedHeap()
    {
        var processor = new ZeroAllocCombatProcessor();
        var pool = new List<CombatTargetData>
        {
            new(1, 100, 10f),
            new(2, 50, 5f),
            new(3, 20, 15f),
            new(4, 0, 2f),
            new(5, 75, 8f)
        };
        var buffer = new CombatTargetData[4];

        // JIT warm-up execution before profiling
        processor.FilterAndSelectTopTargetsNonAlloc(pool, buffer, 20f, 30, out _);

        long beforeAlloc = GC.GetAllocatedBytesForCurrentThread();
        int count = processor.FilterAndSelectTopTargetsNonAlloc(pool, buffer, 20f, 30, out int criticalId);
        long afterAlloc = GC.GetAllocatedBytesForCurrentThread();

        Assert.AreEqual(4, count);
        Assert.AreEqual(3, criticalId);
        Assert.AreEqual(0, afterAlloc - beforeAlloc, "FilterAndSelectTopTargetsNonAlloc must strictly allocate zero bytes on the Managed Heap!");
    }

    [Test]
    public void FilterAndSelectTopTargetsNonAlloc_WhenBufferSmallerThanPool_ClampsSafely()
    {
        var processor = new ZeroAllocCombatProcessor();
        var pool = new List<CombatTargetData>
        {
            new(1, 100, 2f),
            new(2, 100, 3f),
            new(3, 100, 4f)
        };
        var smallBuffer = new CombatTargetData[2];

        int count = processor.FilterAndSelectTopTargetsNonAlloc(pool, smallBuffer, 10f, 10, out _);

        Assert.AreEqual(2, count);
        Assert.AreEqual(1, smallBuffer[0].Id);
        Assert.AreEqual(2, smallBuffer[1].Id);
    }

    [Test]
    public void FilterAndSelectTopTargetsNonAlloc_NullOrEmptyInputs_ReturnsZero()
    {
        var processor = new ZeroAllocCombatProcessor();
        var buffer = new CombatTargetData[4];

        Assert.AreEqual(0, processor.FilterAndSelectTopTargetsNonAlloc(null, buffer, 10f, 10, out int crit1));
        Assert.AreEqual(-1, crit1);
        Assert.AreEqual(0, processor.FilterAndSelectTopTargetsNonAlloc(new List<CombatTargetData>(), null, 10f, 10, out int crit2));
        Assert.AreEqual(-1, crit2);
    }
}

4. Engineering Trade-offs Analysis

Optimizing memory efficiency always incurs specific design compromises. Developers should avoid dogmatic avoidance of modern language features and instead deploy them appropriately:

Technique / Architectural ChoiceKey AdvantagesTrade-offs & LimitationsRecommended Context
Generic Constraints (where T : struct)Eliminates 100% of boxing overhead; dispatches directly on the CPU stack; eliminates mutation bugs.Moderate binary code size expansion (IL2CPP Code Bloat due to type specialization); more verbose method signatures.Mandatory for core runtime interfaces (Combat, Damage, Event Bus) evaluated every frame.
Index Loops & NonAlloc Buffers0 bytes GC Alloc; maximizes CPU Data Cache utilization through contiguous memory layout.Enforces a fixed maximum capacity (capacity), requiring clamping logic if entity counts surge; requires more lines of code.Mandatory in Update, FixedUpdate, AI Pathfinding, and Combat Detection loops.
LINQ & Lambda ExpressionsClean, declarative syntax; enhances readability and accelerates feature prototyping.Allocates iterator objects, delegates, and boxed enumerators across the Managed Heap.Well-suited for Unity Editor tooling, offline asset baking, and initialization logic executed once during load time.
CompareTag & TextMeshPro SetTextAvoids intermediate managed string allocations; performs rapid comparison at the native C++ level.Requires discipline in adopting specific API conventions over the standard + concatenation operator.Mandatory for real-time HUD counters, health bars, and high-frequency collision tag checks.

5. Practical Takeaways

Memory optimization in Unity is not about banning modern C# features wholesale. Rather, it requires establishing a clear boundary across the codebase:

  1. Cold Path (one-time or low-frequency execution): Scene initialization, configuration loading, Editor tools, and modal UI setup. Here, maintainability, expressive syntax, and developer velocity take precedence. LINQ and lambdas are entirely acceptable.
  2. Hot Path (60 FPS game loop): Update(), FixedUpdate(), physics queries, navigation logic, and combat calculations. Here, strict discipline is non-negotiable: prevent boxing, avoid capturing lambdas, replace LINQ with pre-allocated buffers, and eliminate string formatting.

In your current production projects, which hidden allocation trap previously caused the most elusive GC Spikes during device profiling?


Share this post:
Lương Bảo Toàn

Luong Bao Toan

I work in HMI Automotive and Game development, sharing knowledge, hands-on experience, and stories I find interesting throughout my journey.

Did this article bring you value?

If this article helped your work, or you simply enjoyed it and want to support me, you can

Buy me a coffee

Related Articles

Comments & Discussions

Powered by Giscus

Get New Posts via Email

Subscribe to stay updated and never miss new posts from me.

* No spam. You can unsubscribe at any time with a single click.