CodeBlanks Logo Icon CodeBlanks

Large Object Heap

C# course · Expert · Lesson 5/47

Learn the Large Object Heap (LOH) and large object behavior.

The Large Object Heap (LOH)

The Large Object Heap (LOH) is a separate heap that holds objects larger than about 85,000 bytes. Large arrays (byte[100000]) and big strings are allocated there.

Objects on the LOH behave like Gen 2; they are not collected in Gen 0/1 collections. LOH allocations are costly and must be used carefully to avoid fragmentation.

The LOH and compaction

When the Small Object Heap (SOH) is collected, memory is compacted and free gaps are merged. Compaction on the LOH is expensive, so it is usually skipped; only a free list is kept.

Since .NET 4.5.1 you can set GCSettings.LargeObjectHeapCompactionMode = CompactOnce to compact the LOH on the next collection. This reduces fragmentation in long-running services.

Exercise Check the LOH

In Main allocate a large array with byte[] buf = new byte[100000];. Check whether it lands on the LOH with bool isLarge = buf.Length > 85000;. Print Console.WriteLine($"LOH: {isLarge}");.

Show example solution
{isLarge}");
Example solution:
using System;

class Program
{
    static void Main()
    {
        byte[] buf = new byte[100000];
        bool isLarge = buf.Length > 85000;
        Console.WriteLine($"LOH: {isLarge}");
    }
}

Test yourself

  1. When does an object go to the LOH?

    • Always
    • Only if it is a struct
    • When its size exceeds ~85,000 bytes
    • When the GC marks it
    Show answer

    When its size exceeds ~85,000 bytes — Correct. Objects above ~85 KB are allocated on the LOH.

  2. Match the heap types

    SOH (Small Object Heap)
    Gen 0/1/2 objects
    LOH (Large Object Heap)
    ~85 KB+ objects
    LargeObjectHeapCompactionMode
    LOH compaction
    Gen 2
    Long-lived objects
  3. Allocate a LOH array

    byte[] buf = ____ byte[100000];
    Show answer
    byte[] buf = new byte[100000];

All lessons in Expert