Skip to content
ToanLB
Go back

Instantiate and Destroy in Unity: Is GC Really the Most Expensive Cost?

~15 min read
Instantiate and Destroy in Unity: Is GC Really the Most Expensive Cost?

During game development with Unity, almost every engineer encounters this scenario: the player activates an ultimate ability, a swarm of enemies spawns into the room, or a cluster bomb detonates, and the frame rate drops noticeably for a brief moment.

Opening the Unity Profiler reveals a conspicuous red spike under Instantiate or Destroy. Accompanying this spike is a small memory figure in the GC Alloc column. Naturally, a familiar assumption follows: “Instantiate and Destroy generate garbage on the heap, triggering the Garbage Collector and freezing the game. We need an Object Pool immediately to eliminate GC allocations!”

However, examining the raw CPU Profiler numbers reveals an intriguing paradox. A single Instantiate call cloning a complex prefab can easily consume 8ms to 15ms of Main Thread execution time, while the reported GC Alloc is merely 1KB to 2KB. In Unity’s C# environment, allocating 1KB of memory is managed by the Boehm GC via size-segregated free lists. While this can cause memory fragmentation or thread lock contention when memory is exhausted, on an established Managed Heap, it executes swiftly and accounts for only a minor fraction of the frame time.

Where does the remaining 95% of that CPU time go? Why does calling Destroy fail to reduce total process RAM on mobile devices immediately? Is Garbage Collection genuinely the primary bottleneck, or has it merely taken the blame for massive workloads occurring deep within Unity’s C++ Native Engine?


The Core Architecture: Dual Memory and the Managed Shell

To diagnose the true cost of Instantiate and Destroy, we must first examine Unity’s Dual Memory Architecture.

Whenever we manipulate an object inheriting from UnityEngine.Object (such as GameObject, Transform, MonoBehaviour, Rigidbody, or MeshRenderer), the entity actually exists across two distinct memory regions:

flowchart LR
    subgraph MANAGED["1. Managed Heap (C# Runtime)"]
        direction TB
        M1["Managed Shell (C# Wrapper)"]
        M2["IntPtr m_CachedPtr (8-byte pointer)"]
        M3["Pure C# Member Fields"]
        M1 --> M2
        M1 --> M3
    end

    subgraph NATIVE["2. Native C++ Memory (Unity Engine)"]
        direction TB
        N1["Native GameObject C++"]
        N2["Native Transform Hierarchy"]
        N3["Mesh Data, PhysX Body, Render State"]
        N1 --> N2
        N1 --> N3
    end

    M2 -->|"Internal Call (icall) Pointer"| N1
  1. Native C++ Object: The core execution state of the object (geometry data, Transform matrix calculations, Scene Graph links, PhysX bounding boxes, and rendering state) resides completely inside Unity’s C++ engine core, allocated via specialized native heap allocators.
  2. Managed Shell (C# Wrapper): A lightweight C# instance living on the Managed Heap. Its primary role is storing an IntPtr m_CachedPtr pointing directly to the underlying C++ structure via Internal Calls (icall), alongside any user-defined script fields.

When the Unity Profiler attributes GC Alloc to Instantiate, that figure represents the allocation of these Managed Shells so that C# code can reference the newly created native objects. This allocation is typically only 40 to 80 bytes per component.

The true workload freezing the Main Thread happens entirely within the C++ layer.


Dissecting the 4 Hidden Costs of Instantiate

Calling Instantiate(prefab) is not a simple block memory copy (memcpy). Instead, the engine executes a synchronous pipeline on the Main Thread:

flowchart LR
    subgraph PHASE1["1. C++ Clone & Fixup"]
        direction TB
        P1A["Serialize Prefab into Binary Buffer"]
        P1B["Deserialize into Native C++ Objects"]
        P1C["Patch Internal vs External References"]
        P1A --> P1B --> P1C
    end

    subgraph PHASE2["2. Scene & Hierarchy"]
        direction TB
        P2A["Attach to Scene Graph"]
        P2B["Recalculate World Transform Matrix"]
        P2C["Register into PhysX BVH & Culling"]
        P2A --> P2B --> P2C
    end

    subgraph PHASE3["3. Lifecycle Dispatch"]
        direction TB
        P3A["Create Managed Shells on Heap"]
        P3B["Native-to-Managed Thunk Call"]
        P3C["Synchronously Invoke Awake & OnEnable"]
        P3A --> P3B --> P3C
    end

    PHASE1 --> PHASE2 --> PHASE3

1. Deserialization and the Reference Fixup Pass

A Prefab asset stored on disk or loaded into RAM is structured as a serialized binary data stream.

When cloning, Unity deserializes this data stream to reconstruct the C++ object tree. Once the new native objects are created, the engine executes a comprehensive graph traversal called the Reference Fixup Pass:

If a prefab features a deeply nested hierarchy (5 to 7 levels deep) containing dozens of components and cross-references, this pointer remapping traversal scales significantly in CPU overhead.

2. Native C++ Memory Allocation

Unlike the Managed Heap which resolves memory from managed free lists, Unity’s C++ native allocators allocate dynamic blocks from system memory pools.

Every Transform, MeshFilter, MeshRenderer, BoxCollider, and AudioSource requires distinct native memory allocations with metadata headers, thread synchronization guards, and fragmentation management. Performing dozens of native allocations is substantially more CPU-intensive than allocating a few C# objects on the managed heap.

3. Subsystem Registration: Transform, Physics, and Culling

Once created, an object must be registered into several engine subsystems:

4. Managed Shell Creation and Lifecycle Dispatch

After native setup finishes, the engine allocates the C# Managed Shells on the Managed Heap and issues native-to-managed thunk calls to invoke Awake() and OnEnable() sequentially.

This is where custom gameplay code frequently compounds the bottleneck:

Accumulating these operations in the same frame as Instantiate pushes the Main Thread past the 16.6ms budget, resulting in a visible stutter.

Classic Optimization Technique: Inactive Prefab Instantiation

Based on the lifecycle dispatch mechanism above, experienced Unity engineers leverage a classic production technique: Instantiating a Prefab in an Inactive State (prefab.activeSelf == false).

When the prefab asset itself is saved in an inactive state (unchecking the active toggle in the Prefab Inspector), calling Instantiate(inactivePrefab) performs complete C++ native deserialization and pointer remapping, but Unity completely bypasses invoking Awake() and OnEnable() during that frame.

This delivers substantial architectural benefits:

  1. You can inject dependencies, assign initialization parameters, and configure state cleanly without lifecycle race conditions between scripts.
  2. You can activate gameObject.SetActive(true) on subsequent frames or stagger activations across multiple ticks, eliminating synchronous frame spikes caused by simultaneous script initialization.

Common Myth: Does Instantiate Upload Data to the GPU?

A frequent misconception among developers is that Instantiate transfers 3D mesh vertices and textures to GPU VRAM during spawning.

It does not.

Meshes, Textures, Shaders, and AudioClips are immutable shared assets. When a prefab is loaded into memory (via Scene loading, Addressables, or AssetBundles), mesh buffers and texture mipmaps are already uploaded to VRAM.

A clone spawned via Instantiate simply receives handles referencing those pre-existing GPU buffers. No duplicate VRAM allocation or PCIe bus transfer takes place during instantiation.

Spikes mistakenly attributed to the GPU usually stem from two specific culprits:

  1. Shader Variant Compilation: If the newly spawned object uses a combination of shader keywords never rendered before in the current session, the GPU graphics driver must compile the shader to device bytecode immediately prior to the draw call.
  2. Accidental renderer.material Access: Accessing renderer.material instead of sharedMaterial or a MaterialPropertyBlock causes Unity to clone the Material in C++ at runtime. This causes native allocations, destroys SRP Batcher eligibility, and triggers a SetPass Call spike.

Dissecting Destroy: Deferred Execution and the “Fake Null” Trap

What happens when calling Destroy(myObject)?

Many expect immediate memory release. In reality, Unity employs deferred destruction:

flowchart LR
    subgraph CALL["1. Call Destroy()"]
        direction TB
        C1["Add to Destruction Queue"]
        C2["Object Stays Valid in Current Frame"]
        C1 --> C2
    end

    subgraph CLEANUP["2. End of Frame Cleanup"]
        direction TB
        D1["Detach from Hierarchy & Physics"]
        D2["Deallocate Native C++ Object"]
        D3["Set IntPtr m_CachedPtr = 0"]
        D1 --> D2 --> D3
    end

    subgraph LEAK["3. Fake Null Trap"]
        direction TB
        L1["myObj == null evaluates to true"]
        L2["Managed Shell Remains on Heap"]
        L3["Uncollected While References Exist"]
        L1 --> L2 --> L3
    end

    CALL --> CLEANUP --> LEAK

Why Does Unity Defer Destruction?

If Unity immediately destroyed the native C++ object when Destroy was called, any subsequent script executing later in the same frame (e.g. in Update or LateUpdate) accessing that object would trigger a fatal use-after-free error or crash the process.

Therefore, Unity places the object into a destruction queue. Actual deallocation occurs at the end of the frame (after Update and LateUpdate loops conclude, right before rendering):

The “Fake Null” Hazard and Leaked Managed Shells

Unity intentionally overrides the equality operator == for UnityEngine.Object. When writing:

// Helper illustrating the divergence between Unity and .NET CLR equality
public class FakeNullInspector
{
    public static void DemonstrateFakeNull(Component targetComponent)
    {
        // Assume targetComponent was destroyed and its C++ Native object freed at frame end
        
        // 1. Unity's overloaded == checks native pointer state (m_CachedPtr == 0)
        // Returns true because the native C++ object is dead!
        bool isUnityNull = (targetComponent == null);

        // 2. Pure .NET reference equality inspects the Managed Heap directly
        // Returns false if the C# Managed Shell remains alive due to lingering references!
        bool isRealNull = object.ReferenceEquals(targetComponent, null);
    }
}

Unity’s == operator does not check whether the C# object is null on the Managed Heap. Instead, it inspects whether the native pointer m_CachedPtr points to null or a destroyed sentinel.

If the native object has been destroyed, targetComponent == null returns true. However, if your C# codebase retains a reference to targetComponent (inside a List<T>, a dictionary, a static field, or an unsubscribed C# event delegate), the Managed Shell remains alive on the Managed Heap.

This condition is termed a Leaked Managed Shell. The Garbage Collector cannot reclaim it because an active GC Root still holds a strong reference to the wrapper. Any arrays, strings, or member variables allocated inside that component remain stuck in memory.


Production Code Sample: From Naive Emitting to Controlled Lifecycles

Consider a concrete production scenario: A fast-paced top-down swarm shooter firing hundreds of energy projectiles per second.

Technical constraints require maintaining a steady 60 FPS on mid-range mobile devices, keeping frame time below 16.6ms, and achieving zero GC allocations within the combat simulation loop.

Initial Approach: High Overhead via Direct Instantiation

During rapid prototyping, spawning directly on firing and calling Destroy on impact is standard:

using UnityEngine;

// Initial prototype approach: Synchronous instantiate and destroy loop
public class NaiveProjectileEmitter : MonoBehaviour
{
    [SerializeField] private GameObject _projectilePrefab;
    [SerializeField] private Transform _firePoint;
    [SerializeField] private float _projectileLifetime = 2.0f;

    public void FireBullet(Vector3 direction, float speed)
    {
        // BOTTLENECK: Consumes Main Thread CPU for C++ Deserialization,
        // native memory allocations, Transform hierarchy updates, and PhysX BVH
        GameObject bullet = Instantiate(_projectilePrefab, _firePoint.position, Quaternion.identity);
        
        Rigidbody rb = bullet.GetComponent<Rigidbody>();
        if (rb != null)
        {
            rb.linearVelocity = direction * speed;
        }

        // PERFORMANCE & LEAK TRAP: Projectile stays alive in the scene for 2 seconds,
        // consuming Transform and PhysX broadphase CPU before entering the end-of-frame
        // destruction queue 2 seconds later. If any script retains 'bullet', it leaks!
        Destroy(bullet, _projectileLifetime);
    }
}

At 100 projectiles active simultaneously, every frame triggers overlapping allocations and deallocations. The Main Thread struggles with graph deserialization and hierarchy recalculation, resulting in frame rate drops even with minimal GC Alloc.

Architecture Solution: Lifecycle Management and State Reset with UnityEngine.Pool

To eliminate the bottleneck, we:

  1. Create a PooledProjectile component attached to the prefab, resetting Rigidbody and TrailRenderer state cleanly upon return.
  2. Utilize UnityEngine.Pool.ObjectPool<T> (integrated in Unity 2021+ through Unity 6) with collectionCheck enabled to catch duplicate release bugs.
  3. Synchronize gameObject.SetActive() transitions with explicit state reset contracts.
using UnityEngine;
using UnityEngine.Pool;

// Component attached directly to the projectile prefab
public class PooledProjectile : MonoBehaviour
{
    [SerializeField] private Rigidbody _rigidbody;
    [SerializeField] private TrailRenderer _trailRenderer;

    private IObjectPool<PooledProjectile> _pool;
    private float _lifetime;
    private float _timer;

    public void SetPool(IObjectPool<PooledProjectile> pool)
    {
        _pool = pool;
    }

    public void OnSpawn(Vector3 position, Vector3 direction, float speed, float lifetime)
    {
        transform.position = position;
        transform.forward = direction;
        _lifetime = lifetime;
        _timer = 0f;

        if (_rigidbody != null)
        {
            _rigidbody.linearVelocity = direction.normalized * speed;
            _rigidbody.angularVelocity = Vector3.zero;
        }
    }

    // MANDATORY: Reset residual physics and graphics state before returning to pool
    public void OnDespawn()
    {
        // 1. Reset residual velocity so recycled bullet does not inherit previous momentum
        if (_rigidbody != null)
        {
            _rigidbody.linearVelocity = Vector3.zero;
            _rigidbody.angularVelocity = Vector3.zero;
        }

        // 2. Clear trail renderer to avoid visual lines stretching across the screen
        if (_trailRenderer != null)
        {
            _trailRenderer.Clear();
        }
    }

    private void Update()
    {
        _timer += Time.deltaTime;
        if (_timer >= _lifetime)
        {
            ReturnToPool();
        }
    }

    public void ReturnToPool()
    {
        if (_pool != null)
        {
            _pool.Release(this);
        }
    }
}

// Production projectile emitter using UnityEngine.Pool.ObjectPool
public class OptimizedProjectileEmitter : MonoBehaviour
{
    [SerializeField] private PooledProjectile _projectilePrefab;
    [SerializeField] private Transform _firePoint;
    [SerializeField] private int _defaultCapacity = 50;
    [SerializeField] private int _maxPoolSize = 200;

    private IObjectPool<PooledProjectile> _pool;

    private void Awake()
    {
        // Initialize standard Unity ObjectPool (Unity 2021+ & Unity 6)
        _pool = new ObjectPool<PooledProjectile>(
            createFunc: CreatePooledItem,
            actionOnGet: OnTakeFromPool,
            actionOnRelease: OnReturnedToPool,
            actionOnDestroy: OnDestroyPoolObject,
            collectionCheck: true, // Throws exception if code mistakenly releases an item twice
            defaultCapacity: _defaultCapacity,
            maxSize: _maxPoolSize
        );
    }

    private PooledProjectile CreatePooledItem()
    {
        var projectile = Instantiate(_projectilePrefab);
        projectile.SetPool(_pool);
        return projectile;
    }

    private void OnTakeFromPool(PooledProjectile projectile)
    {
        projectile.gameObject.SetActive(true);
    }

    private void OnReturnedToPool(PooledProjectile projectile)
    {
        projectile.OnDespawn();
        projectile.gameObject.SetActive(false);
    }

    private void OnDestroyPoolObject(PooledProjectile projectile)
    {
        Destroy(projectile.gameObject);
    }

    public void FireBullet(Vector3 direction, float speed, float lifetime)
    {
        PooledProjectile bullet = _pool.Get();
        bullet.OnSpawn(_firePoint.position, direction, speed, lifetime);
    }
}

Automated Verification with NUnit

We verify lifecycle management, residual velocity resets, and collectionCheck safety through NUnit:

using System;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.Pool;

// Independent lifecycle contract for testing
public interface IResettableProjectile
{
    bool IsActive { get; }
    Vector3 Position { get; }
    Vector3 Velocity { get; }
    void Initialize(Vector3 position, Vector3 direction, float speed);
    void ResetPhysicsAndTrail();
}

// Mock simulation class for isolated unit testing
public class MockSimulationProjectile : IResettableProjectile
{
    public bool IsActive { get; private set; }
    public Vector3 Position { get; private set; }
    public Vector3 Velocity { get; private set; }

    public void Initialize(Vector3 position, Vector3 direction, float speed)
    {
        Position = position;
        Velocity = direction.normalized * speed;
        IsActive = true;
    }

    public void ResetPhysicsAndTrail()
    {
        Position = Vector3.zero;
        Velocity = Vector3.zero;
        IsActive = false;
    }
}

[TestFixture]
public class ProjectilePoolLifecycleTests
{
    [Test]
    public void ObjectPool_GetAndSpawn_InitializesVelocityCorrectly()
    {
        var pool = new ObjectPool<MockSimulationProjectile>(
            createFunc: () => new MockSimulationProjectile(),
            actionOnGet: p => {},
            actionOnRelease: p => p.ResetPhysicsAndTrail(),
            actionOnDestroy: null,
            collectionCheck: true,
            defaultCapacity: 10,
            maxSize: 50
        );

        var bullet = pool.Get();
        bullet.Initialize(Vector3.zero, Vector3.forward, 30f);

        Assert.IsTrue(bullet.IsActive);
        Assert.AreEqual(new Vector3(0, 0, 30), bullet.Velocity);
        Assert.AreEqual(Vector3.zero, bullet.Position);
    }

    [Test]
    public void ObjectPool_Release_ResetsResidualVelocityToZero()
    {
        var pool = new ObjectPool<MockSimulationProjectile>(
            createFunc: () => new MockSimulationProjectile(),
            actionOnGet: null,
            actionOnRelease: p => p.ResetPhysicsAndTrail(),
            actionOnDestroy: null,
            collectionCheck: true,
            defaultCapacity: 5,
            maxSize: 20
        );

        var bullet = pool.Get();
        bullet.Initialize(new Vector3(10, 5, 2), Vector3.up, 50f);

        // Return to pool: verify velocity and state are wiped clean
        pool.Release(bullet);

        Assert.IsFalse(bullet.IsActive);
        Assert.AreEqual(Vector3.zero, bullet.Velocity);
        Assert.AreEqual(Vector3.zero, bullet.Position);
    }

    [Test]
    public void ObjectPool_DoubleRelease_ThrowsInvalidOperationException()
    {
        var pool = new ObjectPool<MockSimulationProjectile>(
            createFunc: () => new MockSimulationProjectile(),
            actionOnGet: null,
            actionOnRelease: p => p.ResetPhysicsAndTrail(),
            actionOnDestroy: null,
            collectionCheck: true, // collectionCheck detects duplicate release
            defaultCapacity: 5,
            maxSize: 10
        );

        var bullet = pool.Get();
        pool.Release(bullet);

        // Second release must throw exception
        Assert.Throws<InvalidOperationException>(() =>
        {
            pool.Release(bullet);
        });
    }

    [Test]
    public void ObjectPool_ExceedingMaxSize_DestroysOverflowInstance()
    {
        int destroyedCount = 0;
        var pool = new ObjectPool<MockSimulationProjectile>(
            createFunc: () => new MockSimulationProjectile(),
            actionOnGet: null,
            actionOnRelease: p => p.ResetPhysicsAndTrail(),
            actionOnDestroy: p => destroyedCount++,
            collectionCheck: true,
            defaultCapacity: 1,
            maxSize: 1
        );

        var b1 = pool.Get();
        var b2 = pool.Get();

        pool.Release(b1);
        pool.Release(b2); // Exceeds maxSize -> triggers actionOnDestroy

        Assert.AreEqual(1, destroyedCount);
    }
}

The Real Cost of Object Pooling: No Free Lunch

While Object Pooling successfully avoids native deserialization and memory allocation, it introduces distinct engineering trade-offs:

1. Overhead of SetActive(true) and SetActive(false)

Recycling an object usually involves toggling gameObject.SetActive(). This operation:

If OnEnable() contains expensive initialization logic or queries, pooling will fail to eliminate frame stutter.

2. Baseline RAM Footprint and High-Water Mark

Direct Instantiate and Destroy allows memory consumption to shrink and expand dynamically. Pre-warming an Object Pool, however, permanently commits both native and managed memory allocations for those instances throughout the entire scene lifecycle.

Over-allocating pools (e.g. reserving 500 enemy prefabs and 2,000 bullets) pushes process memory to a high baseline, increasing Out-Of-Memory termination risks on memory-constrained mobile hardware.

3. Residual State Bugs

When an object is destroyed, its state is wiped. With pooling, the instance is reused as-is. Failing to reset individual properties produces persistent gameplay glitches:


Technical Trade-off Matrix

Technical MetricDirect Instantiate & DestroyStatic Pre-warmed Object PoolDynamic Auto-scaling PoolInstantiateAsync (Unity 6 / 2023+)
Main Thread CPU CostVery High (Spikes under batch spawning)Very Low (Bounded by OnEnable execution)Low during reuse, occasional spikes when expandingVery Low (Workload distributed over multiple frames)
Initial RAM OverheadMinimal (Allocated strictly on demand)High (Memory committed upfront)Moderate (Grows adaptively)Low (Loaded progressively)
Residual State RiskNone (Every instance is fresh)High (Requires explicit manual reset protocol)High (Requires rigorous state handling)None (Creates pristine native instances)
Codebase ComplexitySimplest, minimal maintenanceRequires pool container and reset contractsMost complex (Requires growth and shrinkage policies)Simple, leverages built-in asynchronous API
Optimal Use CaseUnique boss spawns, UI modals, Scene transitionsRapid-fire bullets, enemy swarms, particle impactsHighly fluctuating entity volumesProgressive level streaming, companion character loading

Practical Takeaways

  1. Do not blame the Garbage Collector exclusively: The GC Alloc reported under Instantiate reflects only lightweight C# Managed Shell creation. Over 95% of the frame drop stems from C++ native deserialization, memory allocators, pointer fixups, and PhysX BVH spatial tree updates.
  2. Destroy is deferred: Destruction requests are processed at the end of the frame. Retaining C# references to destroyed entities turns their managed shells into Leaked Managed Shells that evade garbage collection despite myObj == null evaluating to true.
  3. Object Pooling trades RAM for CPU: Pooling avoids native allocations and deserialization, but incurs hierarchy traversal costs during SetActive() and locks memory at a permanent baseline. If a pooled object stutters, audit its OnEnable() implementation.
  4. Leverage modern asynchronous instantiation: When spawning heavyweight entities that cannot be pooled, utilize Unity 6’s Object.InstantiateAsync() to offload deserialization and native setup to worker threads, safeguarding Main Thread frame pacing.

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.