Skip to content
ToanLB
Go back

Object Pool Keeps Bloating: How to Solve Pool Bloat and Peak Memory Retention in Unity

~11 min read
Object Pool Keeps Bloating: How to Solve Pool Bloat and Peak Memory Retention in Unity

In high-density game genres such as Roguelike Swarm, Bullet-hell, or fast-paced Action RPGs on mobile, implementing an Object Pool is virtually a de-facto requirement to eliminate recurring allocation and deallocation overhead inside the main game loop.

However, a serious architectural dilemma arises when gameplay encounters abrupt burst loads: during normal gameplay, the stage maintains around 50 to 80 active bullets and 20 enemies. But when the player triggers an ultimate screen-clearing skill or collects a temporary 10x fire-rate storm buff, projectile count surges to 1,000 bullets and hundreds of collision sparks within 3 to 5 seconds.

To accommodate this momentary surge, the Object Pool dynamically expands (grows) to 1,000 instances. Once the storm passes and combat settles back to baseline, more than 900 surplus instances return to the pool queue. But instead of reclaiming memory, those 900 idle GameObjects continue to lock device RAM at peak levels for the remainder of the session. This phenomenon is known as Pool Bloat, and its direct technical consequence is Peak Memory Retention.

If we attempt a naive cleanup by iterating through a loop to destroy hundreds of idle objects at once, the engine freezes with a severe lag spike. If we ignore it, the mobile operating system terminates the process due to out-of-memory constraints.

In this deep dive, we dissect the underlying Native C++ memory footprint behind Pool Bloat and establish 4 practical strategies to create a self-trimming pool architecture that maintains a rock-solid 60 FPS.


1. Under the Hood: The Native C++ Memory Iceberg

When developers discuss Object Pooling, many instinctively focus on the C# Managed Heap: a class instance containing a few integer/float fields and component references. From that perspective, 1,000 idle GameObjects sitting in a List<T> or Queue<T> seem to consume negligible memory, perhaps only tens of kilobytes.

In reality, the overwhelming majority of a GameObject’s cost resides inside the Native C++ Engine:

flowchart LR
    subgraph MANAGED["1. C# Managed Heap (Small Shell)"]
        direction TB
        M1["GameObject Shell (~56 bytes)"]
        M2["MonoBehaviour Reference"]
        M3["Queue Pool Table"]
        M1 --> M2 --> M3
    end

    subgraph NATIVE["2. Native C++ Engine (Memory Iceberg)"]
        direction TB
        N1["Transform Hierarchy & Matrix Buffer"]
        N2["Mesh & SkinnedMesh Bones Cache"]
        N3["PhysX Broadphase Colliders Tree"]
        N1 --> N2 --> N3
    end

    MANAGED -->|"Strong Native Pointer"| NATIVE

Even when a GameObject is deactivated with SetActive(false):

Why Peak Memory Retention is Fatal on Mobile

On desktop operating systems (Windows, macOS), when physical RAM runs low, the OS pages inactive memory blocks out to disk storage (Virtual Memory / Swap file).

On mobile operating systems (Android and iOS), however, traditional virtual memory swap is not supported for application process space:

  1. Resident Set Size (RSS): The OS tracks the exact physical RAM footprint occupied by your game process.
  2. Memory Pressure Thresholds: When a temporary combat surge elevates process RAM from 600MB to 1.2GB, that 1.2GB remains locked in the Resident Set even after all 900 bullets return to idle.
  3. OS-Enforced Termination (OOM Crash): The moment the user receives an incoming call, opens a notification, or the engine loads a subsequent stage asset, the Android Low Memory Killer (LMK) or iOS jetsam daemon issues a non-catchable SIGKILL signal, instantly terminating the game without leaving any C# exception stack trace!

2. The Naive Cleanup Trap: Synchronous Destruction and CPU Spikes

Upon realizing the danger of Peak Memory Retention, a common knee-jerk reaction is to batch-destroy idle instances as soon as combat subsides:

// NAIVE CLEANUP ANTI-PATTERN: CAUSES SEVERE FRAME DROP
public class NaivePoolCleanupDemo : MonoBehaviour
{
    private readonly Queue<GameObject> _idlePool = new();

    public void OnWaveCompleted()
    {
        // PERFORMANCE TRAP: Destroying hundreds of native objects in a single frame
        while (_idlePool.Count > 50)
        {
            var obj = _idlePool.Dequeue();
            Destroy(obj); // Triggers massive synchronous C++ deallocations
        }
    }
}

This pattern trades one problem for another: CPU Lag Spikes.

As explored in our earlier analysis of engine internals, calling Destroy() in Unity does far more than setting a C# reference to null. It triggers an expensive cascade across Native C++ systems:

Executing this synchronously for 500 to 800 objects within a single frame halts the Unity Main Thread for 100ms to 250ms. Right after the player survives an exhilarating combat encounter, the game visibly stutters and freezes.

To solve both dilemmas simultaneously, we need an adaptive pool system that can regulate its capacity smoothly over time.


3. Four Production Strategies for Adaptive Pool Sizing

The following architecture diagram illustrates how requests flow through capacity validation, hard bounds, FIFO stealing, and time-sliced auto-trimming:

flowchart LR
    A["Request Object"] --> B{"Pool Has Free Instance?"}
    B -->|"Idle Available"| C["Dequeue from Queue & Reset"]
    B -->|"Empty & Exceeds maxSize"| D["FIFO Steal: Reclaim Oldest Active"]
    B -->|"Empty & Below maxSize"| E["Instantiate New Instance"]

    F["Release Object to Pool"] --> G{"Idle >= maxSize?"}
    G -->|"At Capacity"| H["Immediate Overflow Destroy"]
    G -->|"Below Capacity"| I["Enqueue into Idle Queue"]

    I --> J["Combat Cooldown & Idle > Base"]
    J --> K["Time-Sliced Auto-Trim: 1-2 obj/frame"]

This workflow relies on 4 coordinated strategies:

Strategy 1: Hard Bounds (maxSize) and Overflow Eviction

Starting in Unity 2021, UnityEngine.Pool.ObjectPool<T> introduced native capacity controls through defaultCapacity and maxSize.

When the pool reaches maxSize, we apply 3 distinct policies based on object characteristics:

  1. Overflow Destroy: During short-lived bursts, the pool allows temporary instantiation to maintain gameplay fidelity. However, upon calling Release(), if the idle queue is already at maxSize, the pool immediately triggers the actionOnDestroy delegate to delete the surplus native instance rather than holding onto it.
  2. FIFO Stealing (Decals and Debris): Highly effective for bullet impact decals, sword slashes, and spent shell casings. We set a strict limit of 50 instances. When bullet 51 impacts a wall, rather than instantiating a 51st decal, the system reclaims the oldest currently active decal and relocates it to the new hit point. Memory remains permanently capped at exactly 50 instances without the player ever noticing the substitution.
  3. Spawn Dropping: For secondary visual elements like ambient smoke or floating damage numbers, if active instances exceed a safe threshold, the system gracefully drops subsequent spawn requests to safeguard frame rates.

Strategy 2: Time-sliced Auto-Trimming

After a massive wave ends, idle instances often far exceed standard requirements (e.g., 300 idle objects when baseline demands only 50).

The system monitors idle duration. If idle count remains above defaultCapacity after a settling period (e.g., 15 to 20 seconds), a trimming routine activates.

Rather than invoking a synchronous cleanup loop, the trimming routine slices the work across frames using a Coroutine or frame tick: destroying only 1 to 2 idle instances per frame. Reclaiming 250 surplus instances across 2 to 4 seconds smoothly restores baseline Native RAM while preserving an uninterrupted 60 FPS.

Strategy 3: Priority Pooling

Not all pooled objects share the same architectural importance:

Strategy 4: Emergency Defense via Application.lowMemory

Mobile operating systems provide an explicit warning before forcefully killing background or high-memory processes. In Unity, we subscribe to Application.lowMemory.

When this event fires, system RAM has breached a danger threshold. The pool manager immediately triggers an emergency fallback protocol:


4. Production C# Implementation and Unit Testing

To implement these strategies with full testability decoupled from MonoBehaviour dependencies, we design a pure C# coordinator class: BoundedAutoTrimPool<T>.

In a typical Roguelike Swarm project, we manage projectiles and impact decals with strict capacity controls:

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

public interface IPoolItem
{
    bool IsActive { get; set; }
    void ResetState();
}

public class MockBullet : IPoolItem
{
    public int Id { get; }
    public bool IsActive { get; set; }
    public bool WasDestroyed { get; private set; }

    public MockBullet(int id)
    {
        Id = id;
        IsActive = false;
        WasDestroyed = false;
    }

    public void ResetState()
    {
        IsActive = true;
    }

    public void MarkDestroyed()
    {
        WasDestroyed = true;
    }
}

public class BoundedAutoTrimPool<T> where T : class, IPoolItem
{
    private readonly Func<T> _factory;
    private readonly Action<T> _destroyAction;
    private readonly int _defaultCapacity;
    private readonly int _maxSize;

    private readonly Queue<T> _idleQueue = new();
    private readonly List<T> _activeList = new();

    public int IdleCount => _idleQueue.Count;
    public int ActiveCount => _activeList.Count;
    public int TotalCount => IdleCount + ActiveCount;

    public BoundedAutoTrimPool(Func<T> factory, Action<T> destroyAction, int defaultCapacity, int maxSize)
    {
        _factory = factory ?? throw new ArgumentNullException(nameof(factory));
        _destroyAction = destroyAction ?? throw new ArgumentNullException(nameof(destroyAction));
        _defaultCapacity = defaultCapacity;
        _maxSize = maxSize;
    }

    public T Get()
    {
        T item;
        if (_idleQueue.Count > 0)
        {
            item = _idleQueue.Dequeue();
        }
        else
        {
            item = _factory();
        }

        item.ResetState();
        _activeList.Add(item);
        return item;
    }

    public T GetWithFifoSteal()
    {
        // When max capacity is reached and no idle instances remain, steal the oldest active instance
        if (_idleQueue.Count == 0 && TotalCount >= _maxSize && _activeList.Count > 0)
        {
            var oldest = _activeList[0];
            _activeList.RemoveAt(0);
            oldest.ResetState();
            _activeList.Add(oldest);
            return oldest;
        }

        return Get();
    }

    public void Release(T item)
    {
        if (item == null) return;

        _activeList.Remove(item);
        item.IsActive = false;

        // If idle count has reached maxSize, perform immediate overflow destruction
        if (_idleQueue.Count >= _maxSize)
        {
            _destroyAction(item);
        }
        else
        {
            _idleQueue.Enqueue(item);
        }
    }

    public int TrimIdle(int countToTrim)
    {
        int trimmed = 0;
        while (_idleQueue.Count > _defaultCapacity && trimmed < countToTrim)
        {
            var item = _idleQueue.Dequeue();
            _destroyAction(item);
            trimmed++;
        }
        return trimmed;
    }

    public int FlushAllIdle()
    {
        int count = _idleQueue.Count;
        while (_idleQueue.Count > 0)
        {
            var item = _idleQueue.Dequeue();
            _destroyAction(item);
        }
        return count;
    }
}

[TestFixture]
public class BoundedPoolTests
{
    private int _idCounter;
    private readonly List<MockBullet> _destroyedBullets = new();

    private MockBullet CreateBullet() => new(++_idCounter);
    private void DestroyBullet(MockBullet b)
    {
        b.MarkDestroyed();
        _destroyedBullets.Add(b);
    }

    [SetUp]
    public void Setup()
    {
        _idCounter = 0;
        _destroyedBullets.Clear();
    }

    [Test]
    public void Pool_ExceedingMaxSize_TriggersOverflowDestroyOnRelease()
    {
        var pool = new BoundedAutoTrimPool<MockBullet>(CreateBullet, DestroyBullet, defaultCapacity: 2, maxSize: 3);

        var b1 = pool.Get();
        var b2 = pool.Get();
        var b3 = pool.Get();
        var b4 = pool.Get(); // Burst allocation temporarily creates 4th item

        Assert.AreEqual(4, pool.ActiveCount);

        pool.Release(b1);
        pool.Release(b2);
        pool.Release(b3); // Idle pool reaches 3 items (maxSize)

        Assert.AreEqual(3, pool.IdleCount);
        Assert.AreEqual(0, _destroyedBullets.Count);

        // Releasing 4th bullet when idle pool is full triggers overflow destruction
        pool.Release(b4);

        Assert.AreEqual(3, pool.IdleCount);
        Assert.AreEqual(1, _destroyedBullets.Count);
        Assert.IsTrue(b4.WasDestroyed);
    }

    [Test]
    public void FifoSteal_ReusesOldestActiveBullet_WithoutGrowingBeyondMaxSize()
    {
        var pool = new BoundedAutoTrimPool<MockBullet>(CreateBullet, DestroyBullet, defaultCapacity: 1, maxSize: 3);

        var b1 = pool.GetWithFifoSteal();
        var b2 = pool.GetWithFifoSteal();
        var b3 = pool.GetWithFifoSteal();

        Assert.AreEqual(3, pool.TotalCount);
        Assert.AreEqual(1, b1.Id);

        // Spawning 4th bullet steals the oldest active instance (b1) without growing the pool
        var b4 = pool.GetWithFifoSteal();

        Assert.AreEqual(3, pool.TotalCount);
        Assert.AreEqual(b1.Id, b4.Id);
        Assert.AreEqual(0, _destroyedBullets.Count);
    }

    [Test]
    public void AutoTrim_SlicesDestruction_ReducesIdleCountToDefaultCapacity()
    {
        var pool = new BoundedAutoTrimPool<MockBullet>(CreateBullet, DestroyBullet, defaultCapacity: 2, maxSize: 10);

        var bullets = new List<MockBullet>();
        for (int i = 0; i < 6; i++) bullets.Add(pool.Get());
        foreach (var b in bullets) pool.Release(b);

        Assert.AreEqual(6, pool.IdleCount);

        // Frame 1: Trim 2 items
        int trimmed1 = pool.TrimIdle(countToTrim: 2);
        Assert.AreEqual(2, trimmed1);
        Assert.AreEqual(4, pool.IdleCount);

        // Frame 2: Trim next 2 items, reaching defaultCapacity (2)
        int trimmed2 = pool.TrimIdle(countToTrim: 2);
        Assert.AreEqual(2, trimmed2);
        Assert.AreEqual(2, pool.IdleCount);

        // Frame 3: Already at defaultCapacity, no further items destroyed
        int trimmed3 = pool.TrimIdle(countToTrim: 2);
        Assert.AreEqual(0, trimmed3);
        Assert.AreEqual(2, pool.IdleCount);
        Assert.AreEqual(4, _destroyedBullets.Count);
    }

    [Test]
    public void EmergencyLowMemory_FlushesAllIdleInstancesImmediately()
    {
        var pool = new BoundedAutoTrimPool<MockBullet>(CreateBullet, DestroyBullet, defaultCapacity: 5, maxSize: 10);

        var bullets = new List<MockBullet>();
        for (int i = 0; i < 5; i++) bullets.Add(pool.Get());
        foreach (var b in bullets) pool.Release(b);

        Assert.AreEqual(5, pool.IdleCount);

        // Low memory signal triggers complete idle flush
        int flushed = pool.FlushAllIdle();

        Assert.AreEqual(5, flushed);
        Assert.AreEqual(0, pool.IdleCount);
        Assert.AreEqual(5, _destroyedBullets.Count);
    }
}

Architectural Trade-off Matrix: Comparing Pool Sizing Strategies

No single pooling configuration fits every gameplay scenario. Each strategy trades memory overhead against CPU execution budget:

StrategyTechnical BenefitTrade-off and RiskRecommended Context
Unbounded PoolFastest lookup, zero mid-game Destroy overheadIndefinite Peak Memory Retention, high risk of OS terminationHigh-end PC or Console titles with abundant RAM budgets
Hard Bounds & Overflow DestroyCaps maximum RAM footprint, prevents runaway bloatIncurs C++ Native deallocation cost when overflowing items returnSecondary projectiles and mob enemies during transient bursts
FIFO StealingPerfectly flat RAM profile, zero GC Alloc, zero runtime Instantiate or DestroyActive objects disappear abruptly if capacity is configured too lowBullet impact decals, sword slashes, spent shells, hit sparks
Time-sliced Auto-TrimmingReclaims Native RAM post-combat while preventing frame dropsRequires Coroutine or Timer state tracking logicCore pooling system for mid-to-large scale mobile titles

Key Takeaways

In production game engineering, Object Pooling is a powerful optimization technique, not an infinite storage container.

  1. Acknowledge the Native Iceberg: GameObject memory is dominated by Transform hierarchies, vertex/bone buffers, and PhysX structures. Holding thousands of idle instances wastes precious Native RAM.
  2. Always Enforce Hard Bounds: Never allow an object pool to expand without an explicit maxSize on mobile hardware.
  3. Slice Cleanup Work Across Frames: Distribute native deallocations across consecutive frames to protect frame pacing.
  4. Defend Against OS Termination: Treat Application.lowMemory as an essential safety valve to proactively release non-critical assets before the operating system steps in.

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.