Skip to content
ToanLB
Go back

Why Doesn't Mobile Game RAM Decrease After Garbage Collection?

~16 min read
Why Doesn't Mobile Game RAM Decrease After Garbage Collection?

Almost every Unity engineer targeting mobile devices has encountered this perplexing scenario. You connect an iOS or Android device to your development workstation, fire up Xcode Instruments or Android Studio Memory Profiler, and monitor your process memory in real time.

As the player navigates through multiple stages, you observe App Memory (Resident Size or PSS) creeping up steadily from 500MB to 850MB. Concerns about sudden termination by the operating system - through iOS Jetsam or Android LowMemoryKiller - prompt an immediate response. You add a quick debug trigger or drop an explicit call into your code: GC.Collect().

The Unity Profiler confirms that the garbage collection cycle ran. Temporary garbage objects vanish from the C# allocation graph, and the reported used managed memory drops noticeably. However, looking at the operating system memory graph in Xcode Instruments or Android Studio, the 850MB figure remains stubbornly frozen, without relinquishing a single megabyte. Assuming the collector did not finish the job, you trigger GC.Collect() two or three more times. The outcome is predictable: noticeable frame hitches on the device, while total application RAM remains completely unaffected.

Why does overall system RAM fail to decrease even after garbage collection successfully cleans up managed memory? Where is that memory actually allocated, and how do Unity Engine and the underlying operating system manage memory under the hood?


Understanding Operating System Memory: Physical RAM vs Virtual Memory

To untangle this mystery, we must first examine how mobile operating systems manage process memory.

Mobile devices have a fixed pool of physical memory, such as 4GB or 6GB of LPDDR RAM. Applications never interact directly with physical memory addresses. Instead, every launched process runs within an isolated address space provided by the operating system: virtual memory.

flowchart LR
    subgraph VIRT["1. Virtual Address Space (OS)"]
        direction TB
        V1["Reserved Virtual Pages"]
        V2["Committed Dirty Pages"]
        V1 --> V2
    end

    subgraph HEAP["2. Fragmented Managed Heap"]
        direction TB
        H1["Surviving Objects (Pinned)"]
        H2["Free List (Scattered Holes)"]
        H1 -->|"Scattered Layout"| H2
    end

    subgraph ALLOC["3. Large Array Allocation"]
        direction TB
        A1["Requires 2MB Contiguous Block"]
        A2["No Single Slot Fits"]
        A3["Forces Runtime to Request Pages"]
        A1 --> A2 --> A3
    end

    V2 -->|"Supplies Memory Blocks"| H1
    H2 -->|"Cannot Accommodate"| A1

Virtual memory is segmented into fixed-size units known as memory pages - typically 16KB on Apple Silicon / ARM64 iOS and 4KB on many Android devices or x86 systems. When an application requests memory from the operating system (using system calls such as mmap on POSIX systems), the kernel initially reserves an address range. Only when the application actually writes data into those pages does the kernel map (pages in) physical memory frames into the process page table.

From this operating system perspective, three memory metrics are vital:

  1. Virtual Memory Size (VSize): The total virtual address space reserved by the application. On 64-bit platforms, this can easily reach several gigabytes without indicating actual physical RAM consumption.
  2. Resident Set Size (RSS) / Proportional Set Size (PSS) / Dirty Memory: The actual physical RAM mapped into the process that contains dirty, unevictable application data. This is the exact metric monitored by iOS Jetsam and Android LowMemoryKiller. When Dirty Memory exceeds device-specific thresholds, the OS sends a SIGKILL signal, instantly terminating the game without warning.
  3. Paging Out & Memory Compression: You may occasionally notice process RAM dipping slightly during gameplay without any explicit GC invocation. This occurs when the OS compresses dormant memory pages in RAM (via Android zRAM or Apple Memory Compressor) or evicts clean pages (file-backed read-only pages like executable binaries and mapped assets) when physical memory is contested. Notably, mobile operating systems do not support swap partitions to flash storage in order to protect NAND flash lifespan and avoid catastrophic frame drops. Consequently, dirty runtime memory written to RAM cannot be paged out to disk.

When a C# application runs in Unity (under either Mono or IL2CPP), the entire Managed Heap resides inside the virtual memory address space requested by the runtime from the OS.


Under the Hood: Boehm GC and the High-Water Mark Trap

When we invoke GC.Collect() in C#, what actually occurs within the engine?

Unity relies on the Boehm-Demers-Weiser Garbage Collector (Boehm GC). Unlike modern server-grade .NET runtimes featuring generational and compacting collectors, Unity’s Boehm GC possesses two fundamental characteristics:

A frequent inquiry among experienced engineers is: “Given that Unity has enabled Incremental GC by default in Unity 2021 LTS and Unity 6, doesn’t that alleviate fragmentation or reduce RAM?” The definitive answer is no. Incremental GC solely modifies the Marking Phase by distributing mark operations across multiple 2ms to 3ms slices per frame to mitigate Stop-the-World frame hitches. Architecturally, Incremental GC remains anchored to the underlying Boehm GC engine, preserving its strict non-compacting and non-generational design. It does not relocate objects, does not coalesce fragmented free slots, and never returns committed virtual memory pages to the operating system.

The Internal Free List Mechanism

When a C# object dies, Boehm GC does not release those memory addresses back to the host operating system. Instead, it marks those address slots as available and registers them into an internal tracking structure called the Free List.

The next time application code executes a new allocation, the runtime allocator inspects this Free List to locate a free slot matching the requested byte size. If an eligible slot is found, it is reused immediately.

This behavior highlights a foundational reality: Garbage collection cleans up memory exclusively for internal reuse by the Managed Heap, not for releasing virtual memory pages back to the operating system.

The High-Water Mark Trap

The official Unity Documentation on Managed Memory highlights a sobering rule: Unity’s Managed Heap almost exclusively expands during runtime and rarely shrinks.

The Mono or IL2CPP runtime requests virtual memory from the operating system in discrete chunks (memory blocks), commonly sized between 1MB, 2MB, or 4MB. When the Managed Heap requires capacity for a new allocation and the current Free List cannot accommodate it, the runtime executes a system call to request another block from the kernel.

Once memory pages in these blocks are committed (becoming dirty pages), Unity retains them for the remainder of the application lifecycle. The maximum memory footprint ever reached by the Managed Heap during a session is known as the High-Water Mark. Even if 95% of active objects are subsequently collected, that High-Water Mark remains locked, and the host operating system continues tracking those committed pages against your process.


Managed Heap Fragmentation: The Swiss Cheese Phenomenon

If the Managed Heap retains committed memory for reuse, why does it continue expanding over time?

The culprit is Managed Heap Fragmentation, commonly illustrated as the “Swiss cheese” effect where memory becomes riddled with tiny, scattered voids.

Consider this real-world production sequence:

  1. During intensive combat, thousands of short-lived objects are instantiated: temporary data payloads, boxed structs, lambda closures, and formatted damage numbers. These transient objects are interleaved with long-lived structures (such as Player controllers, Singletons, Audio managers, and UI views).
  2. Once the encounter concludes, short-lived objects are collected, leaving behind thousands of tiny empty pockets across the heap. Each hole might span only 32, 64, or 256 bytes, wedged tightly between unmovable long-lived objects because Boehm GC does not compact memory.
  3. Summed together, total vacant capacity in the Free List might appear generous - say, 8MB of aggregate free space.
  4. Suddenly, gameplay triggers a larger buffer allocation, such as decoding a save file or packaging a multiplayer telemetry burst: var telemetryBuffer = new byte[2 * 1024 * 1024]; (2MB).
  5. The byte array requires a single, contiguous block of 2MB in memory. The runtime allocator scans the Free List, but only finds 64-byte fragments. Not a single continuous slot can accommodate 2MB.
  6. The inevitable result: Despite having 8MB of total free memory, the runtime is forced to request an additional 2MB to 4MB memory block from the operating system.

The Managed Heap expands from 16MB to 20MB. When repeated across variable payload sizes, this cycle continuously drives the High-Water Mark upward until the device runs out of physical memory.


Memory Architecture Breakdown: Managed Heap is Just the Tip of the Iceberg

Another common misconception is assuming that the Managed Heap accounts for the majority of a mobile game’s memory footprint.

In modern 2D and 3D mobile games, total process RAM is divided across three distinct layers:

flowchart LR
    subgraph TOTAL["Total Process RAM Measured by OS (e.g. 800MB)"]
        direction TB
        M1["1. Managed Heap C#<br/>30MB - 60MB (4% - 8%)"]
        M2["2. Native VM Memory<br/>30MB - 50MB (IL2CPP Metadata)"]
        M3["3. Native Engine Memory<br/>600MB - 700MB (75% - 88%)"]
        M1 --- M2 --- M3
    end

    subgraph SCOPE["Impact Scope of GC.Collect()"]
        direction TB
        S1["Scans Managed Heap Only"]
        S2["Cannot Release Native Memory"]
        S3["Does Not Return Pages to OS"]
        S1 --> S2 --> S3
    end

    M1 -.->|"Only Target Affected"| S1
  1. Managed Heap (C# Objects): Houses C# class instances, strings, and runtime arrays. In a well-optimized mobile game, the Managed Heap typically ranges between 20MB and 60MB, rarely exceeding 100MB. This represents merely 3% to 8% of the application’s overall memory footprint.
  2. Native VM Memory: Utilized directly by the IL2CPP runtime for type metadata, generic class sharing tables, thread execution stacks, and reflection caches. This is unmanaged memory handled by engine internals.
  3. Native Engine Memory (The True Giant): Dominates 70% to 90% of total mobile game RAM. This layer includes:
    • Textures & RenderTextures: Uncompressed textures or inefficient compression formats (RGBA32 instead of ASTC 4x4 or ASTC 6x6), redundant mipmaps, and render buffers.
    • Meshes: Vertex and Index buffers, particularly meshes marked with Read/Write Enabled that duplicate geometry in both CPU RAM and GPU VRAM.
    • Audio Clips: Audio files configured with Decompress On Load instead of Compressed In Memory or Streaming.
    • Shaders & GPU Pipelines: Compiled shader binaries and graphics command buffers.

When you call GC.Collect(), the invocation operates strictly upon Layer 1 (Managed Heap). It has zero authority over hundreds of megabytes of textures, meshes, and sound banks stationed in Layer 3 (Native Engine Memory).

If you load a new level while failing to unload previous textures, or if Addressables asset handles remain retained without calling Release(), invoking GC.Collect() a hundred times will not free a single byte of native memory.

Furthermore, triggering explicit GC.Collect() calls during active gameplay produces harmful side effects:


Practical Engineering: Controlling Fragmentation with Reusable Buffers and Pooling

To address root causes and prevent runaway heap expansion, the solution centers on:

  1. Eliminating fluctuating array allocations on the Managed Heap to prevent fragmentation.
  2. Reusing memory buffers through pooling patterns and fixed capacity.
  3. Enforcing rigorous lifecycle discipline for Native Assets.

Consider an Action RPG Swarm project.

During dense combat encounters with hundreds of active enemies, the system continuously aggregates combat telemetry and damage events to broadcast over network channels or record into local performance logs. The payload size varies unpredictably: a single target hit requires a few dozen bytes, while an area-of-effect ultimate strike wiping an entire swarm generates payloads of 64KB to 256KB.

Initial Approach: Dynamic Array Allocations Fragmenting the Heap

A naive implementation instantiates a fresh byte array for every outgoing telemetry payload:

using System;
using System.Collections.Generic;

// Naive implementation: Allocating dynamic byte arrays for every telemetry event
public class NaiveCombatTelemetrySender
{
    public void SendCombatEventPayload(int eventId, byte[] rawData)
    {
        // Dynamic allocation with fluctuating byte length every frame
        int payloadSize = rawData.Length + 8;
        byte[] payload = new byte[payloadSize];

        // Copy event ID and raw data into the array
        BitConverter.GetBytes(eventId).CopyTo(payload, 0);
        Buffer.BlockCopy(rawData, 0, payload, 8, rawData.Length);

        // After processing, this array becomes managed garbage.
        // Fluctuating buffer sizes leave thousands of fragmented free slots!
        ProcessOutgoingData(payload);
    }

    private void ProcessOutgoingData(byte[] data)
    {
        // Network dispatch or internal logging
    }
}

At 60 FPS under intensive combat, allocating new byte[payloadSize] with arbitrary sizes interleaved between monster entity lifecycles rapidly fragments the Managed Heap. After 15 minutes of testing, the heap expands by tens of megabytes even though the on-screen enemy count remains stable.

Refactored Solution: ArrayPool and Struct Wrapper

To eliminate transient array allocations, we adopt a buffer reuse strategy leveraging System.Buffers.ArrayPool<T>.Shared.

To prevent forgotten returns that lead to pool depletion or memory leaks, we build a lightweight wrapper struct named PooledBufferHandle<T> implementing IDisposable. This enables engineers to utilize C#‘s using var statement to guarantee deterministic buffer returns upon exiting scope.

Below is the production-ready C# implementation combining pooled buffers with ReadOnlySpan<byte> for zero-alloc data manipulation:

using System;
using System.Buffers;

// Lightweight wrapper struct ensuring rented arrays are returned deterministically.
// Designed with the RAII pattern for local scope with 'using var'; avoid copying the struct across functions.
public readonly struct PooledBufferHandle<T> : IDisposable
{
    private readonly ArrayPool<T> _pool;
    private readonly T[] _array;
    private readonly int _length;

    // TECHNICAL WARNING: Rented arrays from ArrayPool may have an actual length greater than or equal to _length (bucket rounding).
    // Never access RawArray.Length directly. Always operate via Span, Memory, or the Length property!
    public T[] RawArray => _array;
    public int Length => _length;
    public Memory<T> Memory => new(_array, 0, _length);
    public Span<T> Span => new(_array, 0, _length);

    public PooledBufferHandle(ArrayPool<T> pool, int minimumLength)
    {
        if (minimumLength <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(minimumLength), "Requested length must be greater than zero");
        }

        _pool = pool;
        _length = minimumLength;
        _array = _pool.Rent(minimumLength);
    }

    public void Dispose()
    {
        if (_array != null)
        {
            // Return array to pool without clearing primitives to optimize CPU overhead
            _pool.Return(_array, clearArray: false);
        }
    }
}

// Combat telemetry dispatcher utilizing zero-allocation buffer pooling
public class CombatTelemetryDispatcher
{
    private readonly ArrayPool<byte> _pool;
    private int _dispatchedPayloadCount;
    private long _totalDispatchedBytes;

    public int DispatchedPayloadCount => _dispatchedPayloadCount;
    public long TotalDispatchedBytes => _totalDispatchedBytes;

    public CombatTelemetryDispatcher(ArrayPool<byte> customPool = null)
    {
        _pool = customPool ?? ArrayPool<byte>.Shared;
    }

    public PooledBufferHandle<byte> CreatePacketBuffer(int payloadLength)
    {
        return new PooledBufferHandle<byte>(_pool, payloadLength);
    }

    // Encodes event telemetry without heap allocations
    public int DispatchCombatEvent(int eventId, ReadOnlySpan<byte> eventData, Span<byte> outputBuffer)
    {
        int requiredSize = 4 + eventData.Length;
        if (outputBuffer.Length < requiredSize)
        {
            throw new ArgumentException("Output buffer capacity is insufficient for payload", nameof(outputBuffer));
        }

        // Write 4-byte Event ID header
        outputBuffer[0] = (byte)(eventId & 0xFF);
        outputBuffer[1] = (byte)((eventId >> 8) & 0xFF);
        outputBuffer[2] = (byte)((eventId >> 16) & 0xFF);
        outputBuffer[3] = (byte)((eventId >> 24) & 0xFF);

        // Copy event payload directly via Span
        eventData.CopyTo(outputBuffer.Slice(4));

        _dispatchedPayloadCount++;
        _totalDispatchedBytes += requiredSize;
        return requiredSize;
    }
}

Automated Unit Verification with NUnit

To verify that buffer recycling operates correctly without memory leaks across standard and boundary conditions, we validate the architecture with an NUnit test fixture:

using System;
using System.Buffers;
using NUnit.Framework;

[TestFixture]
public class CombatTelemetryDispatcherTests
{
    private CombatTelemetryDispatcher _dispatcher;

    [SetUp]
    public void SetUp()
    {
        _dispatcher = new CombatTelemetryDispatcher();
    }

    [Test]
    public void CreatePacketBuffer_ValidLength_ReturnsBufferWithAdequateCapacity()
    {
        // Standard scenario: requesting 256 bytes buffer
        int requestedSize = 256;
        using var bufferHandle = _dispatcher.CreatePacketBuffer(requestedSize);

        Assert.IsNotNull(bufferHandle.RawArray);
        Assert.AreEqual(requestedSize, bufferHandle.Length);
        Assert.GreaterOrEqual(bufferHandle.RawArray.Length, requestedSize);
    }

    [Test]
    public void Dispose_ReturnsArrayToPool_EnablesBufferReuse()
    {
        // Verifying ArrayPool recycling: rent, return, and rent again
        byte[] firstArray;
        using (var handle1 = _dispatcher.CreatePacketBuffer(128))
        {
            firstArray = handle1.RawArray;
            Assert.IsNotNull(firstArray);
        } // Automatically disposes and returns array to pool

        // Renting equivalent capacity from the same pool
        using var handle2 = _dispatcher.CreatePacketBuffer(128);
        Assert.IsNotNull(handle2.RawArray);
        Assert.GreaterOrEqual(handle2.RawArray.Length, 128);
    }

    [Test]
    public void DispatchCombatEvent_ValidPayload_EncodesDataAccuratelyWithoutHeapAlloc()
    {
        // Simulated 8-byte combat event payload
        byte[] sampleData = new byte[] { 10, 20, 30, 40, 50, 60, 70, 80 };
        int eventId = 0x12345678;

        using var handle = _dispatcher.CreatePacketBuffer(4 + sampleData.Length);
        int writtenBytes = _dispatcher.DispatchCombatEvent(eventId, sampleData, handle.Span);

        Assert.AreEqual(12, writtenBytes);
        Assert.AreEqual(1, _dispatcher.DispatchedPayloadCount);
        Assert.AreEqual(12, _dispatcher.TotalDispatchedBytes);

        // Verify header integrity
        Span<byte> span = handle.Span;
        int parsedId = span[0] | (span[1] << 8) | (span[2] << 16) | (span[3] << 24);
        Assert.AreEqual(eventId, parsedId);

        // Verify payload integrity
        Assert.AreEqual(10, span[4]);
        Assert.AreEqual(80, span[11]);
    }

    [Test]
    public void CreatePacketBuffer_ZeroOrNegativeLength_ThrowsArgumentOutOfRangeException()
    {
        // Boundary conditions: invalid length requests
        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            using var invalidHandle = _dispatcher.CreatePacketBuffer(0);
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            using var negativeHandle = _dispatcher.CreatePacketBuffer(-128);
        });
    }

    [Test]
    public void DispatchCombatEvent_OutputBufferTooSmall_ThrowsArgumentException()
    {
        // Boundary condition: insufficient output buffer capacity
        byte[] payload = new byte[16];
        byte[] smallBuffer = new byte[10]; // Requires at least 4 + 16 = 20 bytes

        Assert.Throws<ArgumentException>(() =>
        {
            _dispatcher.DispatchCombatEvent(1, payload, smallBuffer);
        });
    }
}

Engineering Trade-offs Across Memory Allocation Strategies

Every architectural decision involves calculated compromises. The table below compares the strengths and operational costs of memory management patterns in Unity:

Architectural CriteriaDynamic Allocation (new T[])Buffer Pooling (ArrayPool<T>)Native Memory (NativeArray<T>)
Heap Fragmentation RiskVery high when buffer sizes fluctuate continuouslyNear zero due to size bucket recyclingZero (allocated entirely outside Managed Heap)
Allocation LatencyDegrades over time as heap becomes fragmentedExtremely low via pre-warmed pool borrowingLow, backed by Unity Engine Native Allocators
Boehm GC PressureHigh, constant garbage forces frequent scansMinimal, near zero garbage generated per frameZero GC impact
Implementation ComplexityTrivial, straightforward standard codeRequires lifecycle discipline (IDisposable, using)Requires manual Dispose() and unmanaged tracking
Operational HazardsFrame hitches, unrecoverable heap inflationRisk of retaining buffers past scope or pool exhaustionNative memory leaks if unmanaged buffers are unreleased

Production Profiling: Accurate Diagnostic Workflows

To eliminate guesswork and avoid futile GC.Collect() loops, adopt a structured profiling methodology.

1. Distinguishing Engine Memory Profiler APIs

When building runtime telemetry monitors or debug HUDs, choose the API that reflects the specific layer being investigated:

2. The 3-Snapshot Comparison Strategy Using Unity Memory Profiler

Instead of relying on fluctuating real-time graphs, track genuine leaks using the Unity Memory Profiler package with a three-step differential workflow:

flowchart LR
    subgraph SNAP1["Snapshot 1: Baseline"]
        direction TB
        B1["Clean Main Menu"]
        B2["No Gameplay Assets Loaded"]
        B1 --> B2
    end

    subgraph SNAP2["Snapshot 2: Peak Load"]
        direction TB
        P1["Intense Gameplay Encounter"]
        P2["Enemies, VFX, Audio at Peak"]
        P1 --> P2
    end

    subgraph SNAP3["Snapshot 3: Cool-down"]
        direction TB
        C1["Returned to Main Menu"]
        C2["UnloadUnusedAssets Executed"]
        C1 --> C2
    end

    SNAP1 -.->|"Enter Match"| SNAP2
    SNAP2 -.->|"Exit Match"| SNAP3
    SNAP1 <-->|"Diff: Inspect New Objects"| SNAP3
  1. Snapshot 1 (Baseline): Capture memory at the initial Main Menu state prior to loading gameplay assets.
  2. Snapshot 2 (Peak): Capture memory during maximum combat load with active enemies and visual effects.
  3. Snapshot 3 (Cool-down): Exit the gameplay stage back to the exact initial Main Menu. Trigger full asset cleanup: call Addressables.Release(), invoke Resources.UnloadUnusedAssets(), and capture the third snapshot.

Analysis Workflow: Open the Memory Profiler and execute a Compare Snapshot between Snapshot 1 and Snapshot 3.

Navigate directly to the New Objects tab (objects persisting in Snapshot 3 that were absent in Snapshot 1). These represent genuine memory leak candidates:


Practical Takeaways

Total system RAM remaining unchanged after garbage collection is not an engine malfunction; it is the intentional design of Unity and the host operating system:


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.