What is the Large Object Heap (LOH)?

4 minadvanced.NETLOHgarbage-collectionmemory

Quick Answer

The Large Object Heap holds objects of roughly 85,000 bytes or more (typically large arrays). It's collected only during Gen 2 collections and, by default, is not compacted, so it can fragment over time and cause out-of-memory despite free space. Mitigate by reducing large allocations (pool/reuse buffers, stream data) or occasionally requesting LOH compaction via `GCSettings.LargeObjectHeapCompactionMode`.

Detailed Answer

The Large Object Heap is a special region of the managed heap designed for objects larger than 85,000 bytes (approximately 85 KB).

Key Characteristics:

  1. Separate from Generation 0, 1, 2:

    • LOH is collected only during Gen 2 collections
    • Objects allocated directly to LOH, bypassing Gen 0 and Gen 1
  2. No Compaction (by default):

    • LOH is not compacted during garbage collection (before .NET 4.5.1)
    • Can lead to memory fragmentation
    • From .NET 4.5.1+, can enable compaction
  3. Performance Implications:

// Goes to LOH
byte[] largeArray = new byte[100_000]; // > 85KB

// Stays in regular heap
byte[] smallArray = new byte[80_000];  // < 85KB

Best Practices:

  1. Avoid frequent LOH allocations:
// Bad: Creates LOH allocations repeatedly
for (int i = 0; i < 1000; i++)
{
    byte[] buffer = new byte[100_000];
    ProcessData(buffer);
}

// Good: Reuse large buffers
byte[] buffer = ArrayPool.Shared.Rent(100_000);
try
{
    for (int i = 0; i < 1000; i++)
    {
        ProcessData(buffer);
    }
}
finally
{
    ArrayPool.Shared.Return(buffer);
}
  1. Enable LOH compaction when needed:
GCSettings.LargeObjectHeapCompactionMode = 
    GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
  1. Monitor LOH fragmentation:
long lohSize = GC.GetGCMemoryInfo().HeapSizeBytes;

When LOH Matters:

  • Image processing applications
  • Large buffer operations
  • Video/audio processing
  • Scientific computing with large datasets

Related Resources