Memory management is an important part of building reliable .NET applications. Although the .NET Garbage Collector automatically manages memory, applications can still experience memory pressure when they frequently allocate large objects.
One area that deserves special attention is the Large Object Heap (LOH).
The LOH stores large objects such as byte arrays, character arrays, and other objects that exceed a specific allocation threshold. When an application repeatedly creates large objects, memory consumption can increase, garbage collection can become more expensive, and the application may experience performance problems.
For example, an ASP.NET Core API that processes large file uploads, generates reports, or converts documents into byte arrays may allocate large objects for every request. If multiple requests execute concurrently, the application can allocate a significant amount of memory in a short period.
The challenge is identifying whether the LOH is growing because of legitimate workload requirements, unnecessary allocations, retained references, or memory fragmentation.
This article explains how the Large Object Heap works, how to monitor its growth, and how to investigate large object allocations using .NET diagnostic tools.
Understanding the Large Object Heap
The .NET Garbage Collector divides managed memory into different generations to manage objects based on their lifetime.
The main generations are:
- Generation 0: Stores newly allocated, short-lived objects.
- Generation 1: Stores objects that survive an initial garbage collection.
- Generation 2: Stores long-lived objects that survive multiple collections.
- Large Object Heap: Stores large objects that meet the runtime's large-object allocation threshold.
By default, objects that are approximately 85,000 bytes or larger are allocated on the Large Object Heap. The exact allocation size includes the object's runtime overhead, so an array's element size alone does not determine whether it crosses the threshold.
For example, consider these allocations:
byte[] smallBuffer = new byte[1024];
byte[] largeBuffer = new byte[100_000];
char[] largeCharacters = new char[50_000];
The first array is relatively small and is normally allocated on the small object heap.
The second array requires approximately 100 KB for its elements and is allocated on the LOH.
The character array also requires approximately 100 KB because each character occupies two bytes.
The LOH is treated as part of Generation 2 garbage collection. This means large objects are collected during Gen 2 collections rather than the more frequent Gen 0 collections.
This behavior is important because Gen 2 collections are generally more expensive than collections of younger generations.
Why LOH Growth Can Become a Problem
Allocating large objects is not automatically a performance problem. Applications often need large buffers to process files, images, reports, and other data.
The problem occurs when large allocations happen frequently or remain in memory longer than necessary.
Consider an API that reads an uploaded file into a byte array:
app.MapPost("/upload", async (IFormFile file) =>
{
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
byte[] data = memoryStream.ToArray();
return Results.Ok(new
{
FileSize = data.Length
});
});
For a large upload, this implementation creates a MemoryStream buffer and then creates another array when ToArray is called.
The resulting byte array may be allocated on the LOH. During the copy, both the MemoryStream's internal buffer and the returned array may occupy memory simultaneously.
If several users upload large files at the same time, the application can experience substantial memory allocation.
Common causes of LOH growth include:
- Repeated creation of large byte arrays.
- Loading complete files into memory.
- Converting large streams into byte arrays.
- Generating large JSON responses.
- Processing large images or documents.
- Creating large strings during text processing.
- Keeping large buffers in application caches.
- Retaining references to objects that are no longer required.
The important distinction is between allocation pressure and retained memory. An application can allocate large objects frequently without retaining all of them permanently. It can also retain large objects through caches, static fields, or long-lived references.
These situations require different investigation strategies.
Understand LOH Fragmentation
The LOH has different compaction behavior from the small object heap.
Moving large objects during garbage collection can be expensive. Therefore, the runtime generally does not compact the LOH during ordinary garbage collection.
When large objects become unreachable, the garbage collector can reclaim their space and reuse suitable free blocks for future allocations.
However, free space may be divided into separate blocks. This is known as fragmentation.
For example, imagine the LOH contains several large objects:
LOH Memory Layout
+-------------+-------------+-------------+
| Object A | Object B | Object C |
+-------------+-------------+-------------+
After some objects become unreachable:
+-------------+-------------+-------------+
| Object A | Free Space | Object C |
+-------------+-------------+-------------+
After additional allocations:
+-------------+-------------+-------------+
| Object A | Object D | Free Space |
+-------------+-------------+-------------+
The free space may not be suitable for every new allocation.
This does not mean that every LOH allocation requires compaction. The garbage collector can reuse available free blocks when they are suitable.
However, fragmentation can contribute to allocation difficulties and increased memory pressure.
The runtime provides an option to request LOH compaction during a future full blocking garbage collection. It should not be used as a routine response to every increase in LOH size.
Monitor LOH Growth With dotnet-counters
The first step in investigating LOH growth is monitoring garbage collection and heap size while the application is running.
Install dotnet-counters:
dotnet tool install --global dotnet-counters
Find the running .NET process:
dotnet-counters ps
Start monitoring the application:
dotnet-counters monitor --process-id 12345
Replace 12345 with the actual process ID.
You can also select specific runtime counters:
dotnet-counters monitor \
--process-id 12345 \
--counters System.Runtime
Pay particular attention to the following metrics:
| Metric | Purpose |
|---|
| dotnet.gc.last_collection.heap.size | Shows heap size after the last collection, including the LOH component |
| dotnet.gc.collections | Shows garbage collection activity by generation |
| dotnet.gc.alloc.rate | Shows the managed allocation rate |
| dotnet.process.memory.working_set | Shows the process working set |
| dotnet.gc.heap.fragmentation.size | Shows heap fragmentation where available |
The exact metric names and dimensions can vary between runtime versions.
Interpret the LOH Heap Size
The dotnet.gc.last_collection.heap.size metric includes separate values for different heap generations, including the LOH.
For example, an illustrative output might look like this:
dotnet.gc.last_collection.heap.size
Generation 0 2 MB
Generation 1 5 MB
Generation 2 35 MB
LOH 180 MB
POH 12 MB
This example shows that the LOH occupies 180 MB after the most recent collection.
However, one measurement is not enough to establish a problem.
Monitor the application over time and compare the LOH size before and after garbage collection.
If the LOH repeatedly increases and remains high after Gen 2 collections, investigate whether large objects are being retained.
If the LOH grows rapidly during processing but decreases after collection, the application may be experiencing high allocation pressure rather than a permanent memory leak.
Also remember that the heap-size metric is updated after garbage collection. It does not represent every allocation immediately as it occurs.
Collect GC Heap Snapshots With dotnet-gcdump
Runtime counters tell you whether heap usage is increasing, but they do not provide enough information to identify the object types responsible.
The dotnet-gcdump tool helps inspect managed objects in a running application.
Install it:
dotnet tool install --global dotnet-gcdump
Find available processes:
dotnet-gcdump ps
Collect a heap snapshot:
dotnet-gcdump collect --process-id 12345
You can also specify an output file:
dotnet-gcdump collect \
--process-id 12345 \
--output large-heap.gcdump
The generated GC dump can be opened in supported tools such as Visual Studio or PerfView on Windows.
Compare Multiple Heap Snapshots
One of the most useful techniques is collecting snapshots at different points in time.
For example:
| Snapshot | Application state |
|---|
| Snapshot A | Normal application traffic |
| Snapshot B | After processing multiple large files |
| Snapshot C | After the workload has completed and garbage collection has occurred |
Compare the snapshots and identify which object types have increased.
Pay particular attention to:
- System.Byte[]
- System.Char[]
- System.String
- System.Object[]
- Application-specific buffer classes
- Large collections and report-related objects
For example, if System.Byte[] accounts for a significant portion of the LOH, investigate file processing, image conversion, HTTP response buffering, and serialization code.
If application-specific objects remain in memory, investigate their references and lifetime.
An important operational detail is that collecting a gcdump triggers a Gen 2 garbage collection in the target process. The tool also collects GC events and reconstructs an object-reference graph. This can affect application performance and consume additional memory during collection.
Use it carefully in production, especially when the application already operates close to its memory limit.
Use dotnet-dump to Investigate Retained Objects
When you need deeper information about objects and their references, use dotnet-dump.
Install the tool:
dotnet tool install --global dotnet-dump
Collect a heap dump:
dotnet-dump collect \
--process-id 12345 \
--type Heap \
--output application-heap.dmp
Analyze the collected dump:
dotnet-dump analyze application-heap.dmp
Inside the diagnostic console, execute:
dumpheap -stat
This command displays object statistics, including object counts and total sizes.
For example, you may discover that System.Byte[] occupies a large portion of the managed heap.
You can then inspect objects of a particular type and investigate why they remain reachable.
Use the following command to examine references to a selected object:
gcroot <object-address>
The output helps identify the reference chain that prevents the garbage collector from reclaiming the object.
For example, a large byte array may remain in memory because it is referenced by a static cache, a long-lived service, or an application collection that never removes completed entries.
Heap dumps can contain sensitive application data. Store them securely, restrict access, and avoid transferring them to untrusted locations.
Reduce Large Object Allocations in Application Code
After identifying the source of LOH growth, optimize the allocation pattern.
Use ArrayPool for Reusable Buffers
If an application repeatedly creates large byte arrays of similar sizes, consider using ArrayPool.
ArrayPool allows an application to rent an existing array instead of allocating a new one every time.
using System.Buffers;
public async Task ProcessFileAsync(
Stream inputStream,
CancellationToken cancellationToken)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(128 * 1024);
try
{
int bytesRead;
while ((bytesRead = await inputStream.ReadAsync(
buffer.AsMemory(0, buffer.Length),
cancellationToken)) > 0)
{
await ProcessChunkAsync(
buffer.AsMemory(0, bytesRead),
cancellationToken);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
The buffer is returned in a finally block so that it is available for reuse even if processing fails.
Do not use the rented array after returning it to the pool. Another operation may receive the same array.
Also remember that rented arrays can be larger than the requested size and may contain previous data. Clear sensitive buffers when necessary.
ArrayPool is useful for repeated buffer allocations, but it is not automatically beneficial for every allocation pattern.
Process Large Files as Streams
Avoid loading an entire file into memory when the application can process it in smaller chunks.
Instead of:
byte[] fileData = await File.ReadAllBytesAsync(
filePath,
cancellationToken);
Use a stream:
await using var fileStream = new FileStream(
filePath,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: 81920,
useAsync: true);
byte[] buffer = new byte[81920];
int bytesRead;
while ((bytesRead = await fileStream.ReadAsync(
buffer,
cancellationToken)) > 0)
{
await ProcessChunkAsync(
buffer.AsMemory(0, bytesRead),
cancellationToken);
}
This approach avoids allocating one large byte array for the complete file.
The processing method should also avoid copying every chunk into another large buffer, otherwise the memory benefit may be reduced.
Avoid Unnecessary MemoryStream.ToArray Calls
MemoryStream.ToArray creates a new array containing a copy of the stream's contents.
For large streams, this can create additional LOH allocations.
If the destination API accepts a Stream, pass the stream directly when possible.
If a byte array is genuinely required, consider whether the existing buffer can be accessed safely through an appropriate API rather than creating another copy.
Do not expose an internal MemoryStream buffer beyond its valid lifetime or assume that its capacity equals its actual content length.
Limit Concurrent Large Operations
Even when each individual request uses memory efficiently, too many concurrent large operations can increase total memory consumption.
For example, processing 20 large documents simultaneously may create substantial memory pressure.
Use controlled concurrency when processing memory-intensive workloads.
var options = new ParallelOptions
{
MaxDegreeOfParallelism = 3
};
await Parallel.ForEachAsync(
documentIds,
options,
async (documentId, cancellationToken) =>
{
await ProcessDocumentAsync(
documentId,
cancellationToken);
});
The concurrency limit should be selected based on document size, available memory, CPU capacity, and downstream service limits.
A fixed value is not universally correct. Measure the workload before choosing the appropriate limit.
When Should You Compact the LOH?
The runtime provides GCSettings.LargeObjectHeapCompactionMode to request LOH compaction during the next full blocking garbage collection.
For example:
using System.Runtime;
GCSettings.LargeObjectHeapCompactionMode =
GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(
GC.MaxGeneration,
GCCollectionMode.Forced,
blocking: true,
compacting: true);
This requests compaction during the explicitly triggered full collection.
However, forcing garbage collection in a busy ASP.NET Core application can cause pauses and affect request latency.
LOH compaction is not a replacement for fixing excessive allocations or retained objects. Consider it only when fragmentation has been identified as a real problem and the application can tolerate the collection pause.
Most applications should rely on the runtime's normal garbage collection behavior.
Common Mistakes When Investigating LOH Growth
Avoid these common mistakes:
- Assuming that every increase in LOH size indicates a memory leak.
- Looking only at process working-set memory without checking managed heap metrics.
- Collecting only one heap snapshot instead of comparing snapshots over time.
- Ignoring large byte arrays created during file and image processing.
- Calling ToArray repeatedly when working with large streams.
- Increasing available memory without identifying unnecessary allocations.
- Forcing garbage collection frequently to reduce heap size.
- Using ArrayPool without returning rented buffers.
- Running multiple large operations concurrently without memory limits.
- Ignoring object references that prevent large objects from being collected.
The most reliable investigation combines runtime counters, heap snapshots, allocation analysis, and an understanding of the application's actual workload.
Best Practices for Managing the Large Object Heap
- Monitor LOH size and Gen 2 collection activity in production.
- Use dotnet-gcdump to compare managed heap snapshots.
- Use dotnet-dump when object references need deeper investigation.
- Use streams for large file processing.
- Reuse large buffers with ArrayPool where appropriate.
- Avoid unnecessary byte-array and string copies.
- Limit concurrency for memory-intensive operations.
- Review cache expiration and object retention policies.
- Test large uploads, downloads, and report generation under realistic load.
- Collect diagnostics before making garbage collector configuration changes.
Summary
The Large Object Heap is an important part of .NET memory management. It stores large objects, including arrays and strings that meet the runtime's large-object allocation threshold.
Frequent large allocations, unnecessary copies, retained references, and fragmentation can increase memory pressure and affect application performance.
Start by monitoring LOH size, allocation rate, and Gen 2 collections using dotnet-counters. Then collect heap snapshots with dotnet-gcdump to identify the object types consuming the most memory. Use dotnet-dump when you need to investigate why particular objects remain reachable.
For prevention, process large files as streams, reuse buffers with ArrayPool, avoid unnecessary memory copies, and control the concurrency of memory-intensive operations.
The goal is not simply to reduce the LOH size. It is to understand why large objects are being allocated, determine whether they need to remain in memory, and manage their lifetime efficiently.
Join the conversation! Your thoughts help the community grow.