Skip to content
ToanLB
Go back

Using Structs to Avoid GC Alloc: Are We Actually Flooding the Profiler with Hidden Garbage?

~10 min read
Using Structs to Avoid GC Alloc: Are We Actually Flooding the Profiler with Hidden Garbage?

When optimizing mobile game performance to secure a rock-solid 60 FPS, many Unity developers lean into an intuitive rule of thumb: “Convert data models from classes to structs. Structs are value types allocated on the stack, ensuring zero garbage collection allocation.”

Yet after days of refactoring combat models, projectile telemetry, and character states into structs, opening the Unity Profiler reveals a frustrating reality: the GC Alloc column under Update continues ticking upward with tens of kilobytes per frame. Even worse, the overall frame rate stutters because the CPU gets choked copying memory buffers back and forth.

Why does this paradox happen? How does the C# CLR and Unity IL2CPP runtime handle structs under the hood? This article breaks down struct memory allocation mechanics, identifies four common hidden allocation traps, and examines the trade-off between pass-by-value CPU overhead and cache locality.


1. Deconstructing the Myth: Are Structs Always on the Stack?

One common misconception in C# development is conflating Value Type with always living on the Stack.

In the memory architecture of the .NET CLR and Unity IL2CPP, where a struct actually resides depends strictly on its declaration context and ownership:

flowchart TD
    subgraph S1["1. Local Method Variables"]
        L1["Local Struct<br/>(Update / Calculate Method)"] -->|"Direct allocation"| StackMem["Stack Memory<br/>(Popped upon scope exit)"]
    end

    subgraph S2["2. Fields inside Classes"]
        F1["Struct Field<br/>(Inside MonoBehaviour / Class)"] -->|"Embedded in object"| HeapMem1["Managed Heap<br/>(Shares parent class lifecycle)"]
    end

    subgraph S3["3. Contiguous Struct Arrays"]
        A1["MyStruct[] Array<br/>(Array is a reference type)"] -->|"Contiguous buffer"| HeapMem2["Managed Heap<br/>(Sequential memory alignment)"]
    end

Structs do not automatically guarantee exemption from the managed heap. If handled incorrectly, they trigger boxing and allocate temporary objects on the heap.


2. Four Hidden Traps That Leak Allocations into the Profiler

Before exploring low-level mechanics, let us look at the four primary culprits that turn structs into hidden allocation sources:

flowchart LR
    subgraph BoxingGroup["Heap Boxing Traps"]
        T1["<b>1. Interface Casting</b><br/>• Passing struct to interface<br/>• Missing generic constraint"]
        T2["<b>2. Missing IEquatable&lt;T&gt;</b><br/>• Default ValueType.Equals<br/>• Reflection over fields"]
        T3["<b>3. Dictionary Keys</b><br/>• Dictionary&lt;MyStruct, T&gt;<br/>• EqualityComparer.Default fallback"]
    end

    subgraph ClosureGroup["Scope Capture Traps"]
        T4["<b>4. Lambda Closures</b><br/>• Capturing struct in delegate<br/>• DisplayClass on Heap"]
    end

    BoxingGroup --> ClosureGroup

3. Under the Hood: Dissecting the Four Traps

3.1. Trap 1: Boxing When Casting Structs to Interfaces or System.Object

Consider a combat system defining an interface ICombatReceiver and a struct TargetCombatState. When writing a damage application method that accepts an ICombatReceiver target parameter:

Passing a struct value type to an interface reference type forces the runtime to perform Boxing:

  1. It allocates a new object on the managed heap sized to fit the struct plus an object header (Method Table Pointer and Sync Block Index, consuming 16 bytes on 64-bit architectures).
  2. It copies the raw bytes of the struct from the stack onto that newly minted heap chunk.
  3. Invoking the interface method operates on the boxed heap clone, leaving the original stack instance untouched, triggering both GC garbage and state desynchronization bugs.

The Solution: Use a Generic Constraint such as where T : struct, ICombatReceiver. The compiler generates specialized machine code for struct type T, invoking the method directly without virtual table boxing, achieving zero bytes of GC allocation while mutating the target in-place.


3.2. Trap 2: Omitting Equals, GetHashCode, and IEquatable<T>

When comparing two structs using Equals() without custom overrides, the runtime falls back to System.ValueType.Equals.

Under the hood in the CLR/Mono runtime, System.ValueType.Equals inspects fields via Reflection to compare raw bytes. This reflection routine wastes CPU cycles and boxes the struct into System.Object, generating garbage every time a comparison occurs inside the game loop.

The Solution: Implement IEquatable<T>, override Equals(object), GetHashCode(), and implement the == and != operators. This directs calls directly to the strongly-typed method without boxing or reflection overhead.


3.3. Trap 3: Structs as Dictionary or HashSet Keys

Many caching and inventory systems use coordinate structs as dictionary keys: Dictionary<ItemCoord, InventorySlot>.

If ItemCoord fails to implement IEquatable<ItemCoord>, the dictionary falls back to EqualityComparer<ItemCoord>.Default. This default comparer treats unspecialized structs with ValueType.Equals and ValueType.GetHashCode.

Every single call to TryGetValue() or ContainsKey() inside Update causes boxing allocations just to compute the hash code and evaluate equality.

The Solution: Always implement IEquatable<T> on key structs, or pass a dedicated IEqualityComparer<T> into the dictionary constructor.


3.4. Trap 4: Capturing Structs in Lambda Closures

A common trap occurs when attaching structs to event listeners or callbacks.

When a local value type is captured by an anonymous delegate or lambda expression, the C# compiler generates an internal Display Class on the managed heap. The struct is copied into a field on that heap object, accumulating garbage every time listeners are registered during gameplay.


4. When Structs Degrade Performance: Pass-By-Value and Defensive Copies

Developers often focus on memory allocation while overlooking that Structs are passed by value.

Passing a struct into a method or assigning it to another variable copies its entire memory footprint:

flowchart LR
    subgraph SmallStruct["Small Struct (16 bytes)"]
        S1["Vector3 (12 bytes)<br/>X, Y, Z"] -->|"Register copy"| CPU1["Fast CPU Registers<br/>~1 cycle cost"]
    end

    subgraph BigStruct["Big Struct (128 bytes)"]
        B1["CombatPacket (128 bytes)<br/>16 state fields"] -->|"Stack memcpy"| CPU2["Stack Memory Copy<br/>L1 Cache Bottleneck"]
    end

The 16-Byte Threshold

The Defensive Copy Trap of the in Keyword

To circumvent large copy overhead, C# 7.2 introduced the in modifier for read-only pass-by-reference.

However, if the struct is not marked as readonly struct, the compiler cannot guarantee that invoked methods do not mutate internal state.

To preserve immutability guarantees, the compiler silently creates a defensive copy of the struct on the stack before executing member methods. You write in to prevent copies, yet the compiler introduces hidden copies anyway.

The Solution: Always pair in parameters with readonly struct. This informs the compiler that the struct is immutable, eliminating defensive copying completely.


5. The True Strength of Structs: Cache Locality and Data-Oriented Design

When do structs decisively outperform classes? The primary advantage lies in Contiguous Memory Alignment and CPU Cache Locality:

flowchart TD
    subgraph ClassArray["MyClass[]: Pointer Chasing (Fragmented)"]
        CA["Pointer Array [Heap]"] --> P1["Object 1 [Heap Address 0x1A00]"]
        CA --> P2["Object 2 [Heap Address 0x8F40]"]
        CA --> P3["Object 3 [Heap Address 0x3C10]"]
    end

    subgraph StructArray["MyStruct[]: Contiguous Alignment"]
        SA["Flat Memory [Heap]: [Struct 0][Struct 1][Struct 2][Struct 3]"]
        SA -->|"Loads full 64B Cache Line"| L1["Maximized L1/L2 CPU Cache Hits"]
    end

6. Implementation: From Allocation Traps to Zero-Alloc Architecture

The following real-world combat scenario illustrates how to structure structs and processing pipelines to achieve zero bytes of heap allocation.

6.1. Defining Structs and Interfaces

using System;
using UnityEngine;

public interface ICombatReceiver
{
    int CurrentHp { get; }
    void ReceiveDamage(int amount);
}

// 1. readonly struct eliminates defensive copies when passed with 'in'
// 2. IEquatable<T> eliminates reflection and boxing during equality checks and dictionary lookups
public readonly struct CombatHitData : IEquatable<CombatHitData>
{
    public readonly int HitId;
    public readonly int AttackerId;
    public readonly int BaseDamage;
    public readonly float CritMultiplier;
    public readonly Vector3 HitPoint;

    public CombatHitData(int hitId, int attackerId, int baseDamage, float critMultiplier, Vector3 hitPoint)
    {
        HitId = hitId;
        AttackerId = attackerId;
        BaseDamage = baseDamage;
        CritMultiplier = critMultiplier;
        HitPoint = hitPoint;
    }

    public int CalculateFinalDamage()
    {
        return Mathf.RoundToInt(BaseDamage * Mathf.Max(1f, CritMultiplier));
    }

    public bool Equals(CombatHitData other)
    {
        return HitId == other.HitId &&
               AttackerId == other.AttackerId &&
               BaseDamage == other.BaseDamage &&
               Mathf.Approximately(CritMultiplier, other.CritMultiplier) &&
               HitPoint == other.HitPoint;
    }

    public override bool Equals(object obj)
    {
        return obj is CombatHitData other && Equals(other);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(HitId, AttackerId, BaseDamage, CritMultiplier, HitPoint);
    }

    public static bool operator ==(CombatHitData left, CombatHitData right) => left.Equals(right);
    public static bool operator !=(CombatHitData left, CombatHitData right) => !left.Equals(right);
}

public struct TargetCombatState : ICombatReceiver
{
    public int CurrentHp { get; private set; }

    public TargetCombatState(int initialHp)
    {
        CurrentHp = initialHp;
    }

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

6.2. Zero-Alloc Combat Processor

public static class ZeroAllocCombatEngine
{
    // Generic constraint 'where T : struct, ICombatReceiver' avoids interface boxing
    // Parameter 'in CombatHitData hit' passes by read-only reference without copying the full struct
    public static int ExecuteHit<T>(ref T receiver, in CombatHitData hit) where T : struct, ICombatReceiver
    {
        int finalDamage = hit.CalculateFinalDamage();
        receiver.ReceiveDamage(finalDamage);
        return finalDamage;
    }
}

6.3. Automated NUnit Verification Tests

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

[TestFixture]
public class StructAllocationTests
{
    [Test]
    public void ExecuteHit_ModifiesTargetHp_Accurately()
    {
        var target = new TargetCombatState(100);
        var hit = new CombatHitData(1, 10, 30, 1.5f, Vector3.zero);

        int damageDealt = ZeroAllocCombatEngine.ExecuteHit(ref target, in hit);

        Assert.AreEqual(45, damageDealt);
        Assert.AreEqual(55, target.CurrentHp);
    }

    [Test]
    public void ExecuteHit_WithGenericConstraint_AllocatesZeroBytesOnManagedHeap()
    {
        var target = new TargetCombatState(200);
        var hit = new CombatHitData(2, 10, 20, 1.0f, Vector3.up);

        // Warm up JIT execution
        ZeroAllocCombatEngine.ExecuteHit(ref target, in hit);

        long beforeAlloc = GC.GetAllocatedBytesForCurrentThread();
        ZeroAllocCombatEngine.ExecuteHit(ref target, in hit);
        long afterAlloc = GC.GetAllocatedBytesForCurrentThread();

        Assert.AreEqual(0, afterAlloc - beforeAlloc, "ExecuteHit with generic constraints must allocate exactly zero heap bytes.");
    }

    [Test]
    public void CombatHitData_IEquatable_PreventsBoxingAndEnsuresCorrectEquality()
    {
        var hitA = new CombatHitData(1, 10, 50, 1.2f, new Vector3(1, 2, 3));
        var hitB = new CombatHitData(1, 10, 50, 1.2f, new Vector3(1, 2, 3));
        var hitC = new CombatHitData(2, 10, 50, 1.2f, new Vector3(1, 2, 3));

        Assert.IsTrue(hitA == hitB);
        Assert.IsTrue(hitA.Equals(hitB));
        Assert.IsFalse(hitA == hitC);
        Assert.AreEqual(hitA.GetHashCode(), hitB.GetHashCode());
    }

    [Test]
    public void DictionaryKey_WithIEquatableStruct_AllocatesZeroBytesOnLookup()
    {
        var hitDict = new Dictionary<CombatHitData, int>();
        var hit = new CombatHitData(99, 101, 100, 2.0f, Vector3.zero);
        hitDict[hit] = 1;

        // Warm up JIT execution
        hitDict.TryGetValue(hit, out _);

        long beforeAlloc = GC.GetAllocatedBytesForCurrentThread();
        bool found = hitDict.TryGetValue(hit, out int value);
        long afterAlloc = GC.GetAllocatedBytesForCurrentThread();

        Assert.IsTrue(found);
        Assert.AreEqual(1, value);
        Assert.AreEqual(0, afterAlloc - beforeAlloc, "Dictionary lookup with IEquatable struct keys must generate zero GC allocations.");
    }
}

7. Trade-Off Analysis: Struct vs Class

Selecting between structs and classes involves balancing distinct architectural trade-offs:

CriterionStruct (Value Type)Class (Reference Type)
Default AllocationStack (when local) or embedded in containerAlways on Managed Heap
Garbage Collection CostZero if boxing is avoidedGenerates GC pressure under repeated allocations
Assignment & PassingPass-by-value (copies entire memory buffer)Pass-by-reference (copies 8-byte pointer)
Optimal SizeSmall, ideally 16 bytes or smallerFlexible, suited for complex entities
Passing Large InstancesRequires in with readonly structStandard reference passing
Array Memory AlignmentContiguous buffer with high cache hit ratePointer chasing with frequent cache misses
Polymorphism & HierarchyNo inheritance; polymorphism via genericsSupports virtual methods and class hierarchies
Potential RisksHidden boxing and mutating unintended copiesNullReferenceExceptions and reference leaks

8. Practical Takeaways

To leverage structs effectively without inadvertently saturating the Profiler with garbage:

  1. Avoid treating structs as a magic bullet: Reserve structs for small, short-lived data containers (ideally <= 16 bytes), or large contiguous arrays designed for cache locality.
  2. Enforce generic constraints on interfaces: Always write where T : struct, IMyInterface when invoking interface methods on struct instances to prevent boxing.
  3. Always implement IEquatable<T>: Implement IEquatable<T> and overload == and != to eliminate reflection calls within System.ValueType.Equals.
  4. Mark large structs as readonly struct: If a struct exceeds 16 bytes and must be passed using the in keyword, mark it readonly struct to prevent defensive copies on the stack.
  5. Verify with the Profiler: Validate allocations using the Unity Profiler and memory profiler to confirm that the GC Alloc metric remains at zero bytes across release builds.

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.