Introduction
ASP.NET Core performance is not measured only by how quickly an individual request completes. An endpoint may return quickly while creating large collections, producing unnecessary strings, or keeping resources alive longer than necessary. Under sustained load, these allocations increase garbage collection activity, CPU consumption, and latency.
In this lesson, we will examine memory usage across an ASP.NET Core request. We will start with unnecessary materialization and large collections. Then we will use IAsyncEnumerable<T> to consume data incrementally, streaming responses to avoid building an entire result in memory, and ArrayPool<T> to reduce temporary buffer allocations. Finally, we will apply correct disposal practices and measure allocation and GC behavior with dotnet-counters, dotnet-trace, and BenchmarkDotNet.
1. Recognizing memory bottlenecks
Common signs of memory pressure in an ASP.NET Core application include:
- A working set that continues to grow as traffic increases.
- More frequent Gen 0 and Gen 2 garbage collections.
- High allocation even though the response payload is relatively small.
- Endpoints that load all rows with
ToListAsyncorToArrayAsync. - File streams, response streams, database readers, or timers that remain alive too long.
Not every allocation is a problem. Objects must be created for an application to function. The goal is to remove unnecessary allocations: copying the same data repeatedly, materializing a large entity graph when only a few fields are required, or constructing a complete response string before sending it.
Materialization and allocation
The following code loads every database row into a list. Even if only a few fields are eventually used, all entities, values, and list storage remain in memory:
public async Task<IActionResult> GetProducts(CancellationToken cancellationToken)
{
var products = await _db.Products
.OrderBy(p => p.Id)
.ToListAsync(cancellationToken);
var result = products.Select(p => new ProductSummary(p.Id, p.Name));
return Ok(result);
}A better approach is to project the required fields and avoid materializing more data than necessary:
public async Task<IActionResult> GetProducts(CancellationToken cancellationToken)
{
var result = _db.Products
.AsNoTracking()
.OrderBy(p => p.Id)
.Select(p => new ProductSummary(p.Id, p.Name));
return Ok(await result.ToListAsync(cancellationToken));
}The projection reduces the columns sent from the database. However, if the result set is very large, ToListAsync still stores the complete result in memory. In that case, use pagination or consider streaming.
2. Controlled consumption with IAsyncEnumerable
IAsyncEnumerable<T> lets an asynchronous iterator produce values as they are requested instead of creating the entire sequence at once. This is useful for large datasets, external data sources, and long-running operations. Values are produced with yield return and consumed asynchronously.
public async IAsyncEnumerable<ProductSummary> StreamProducts(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var product in _db.Products
.AsNoTracking()
.OrderBy(p => p.Id)
.Select(p => new ProductSummary(p.Id, p.Name))
.AsAsyncEnumerable()
.WithCancellation(cancellationToken))
{
yield return product;
}
}A controller or minimal API can return the asynchronous sequence:
[HttpGet("stream")]
public IAsyncEnumerable<ProductSummary> GetStream(
CancellationToken cancellationToken)
{
return _service.StreamProducts(cancellationToken);
}Depending on the ASP.NET Core and System.Text.Json version, IAsyncEnumerable<T> can be serialized asynchronously as a JSON array. However, returning an asynchronous sequence does not automatically guarantee that every client receives data immediately. Serializer behavior, buffering, reverse proxies, and client implementation all influence the actual streaming experience. Treat streaming as a measured design choice rather than an automatic optimization.
Why cancellation matters
When a client disconnects or a request times out, the server should stop producing data as soon as possible. Passing the request CancellationToken to the query and using WithCancellation allows the iterator to observe cancellation. Ignoring cancellation can leave CPU and database resources busy even though the client is no longer waiting.
3. Designing a streaming response
When a line-oriented or file-like response is more appropriate than one large JSON list, the response body can be written incrementally. The following example writes newline-delimited JSON:
[HttpGet("events")]
public async Task StreamEvents(CancellationToken cancellationToken)
{
Response.ContentType = "application/x-ndjson";
await foreach (var item in _eventService.ReadAsync(cancellationToken))
{
await JsonSerializer.SerializeAsync(Response.Body, item, cancellationToken: cancellationToken);
await Response.Body.WriteAsync("\n"u8.ToArray(), cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
}This approach does not construct a complete list or a single large string. However, serialization and writing still have a cost for every item. Calling FlushAsync too frequently can also create inefficient network packets. In production, test flush frequency, proxy buffering, client compatibility, and the time to receive the first item.
For files and large binary content, do not manually close the ASP.NET Core response stream. Its lifetime is managed by the framework. A file stream that your code creates is different: the code that owns it must dispose it, or you should use framework-provided file results when appropriate.
4. Reducing string allocations
Strings are immutable, so concatenation can create new objects. Repeated += operations inside a loop can cause unnecessary copying:
var output = "";
foreach (var product in products)
{
output += product.Name + ",";
}When text is built across multiple steps, StringBuilder may be more appropriate:
var builder = new StringBuilder(capacity: 4096);
foreach (var product in products)
{
builder.Append(product.Name).Append(',');
}
var output = builder.ToString();Using StringBuilder everywhere is not automatically faster. For small expressions, ordinary interpolation can be clearer and sufficiently efficient. Measure the real endpoint before applying a micro-optimization. Structured logging also avoids unnecessary message construction:
_logger.LogInformation("Product {ProductId} was updated", productId);Structured logging allows the logging framework to handle values separately and can avoid building an expensive message when the relevant log level is disabled.
5. Temporary buffers with ArrayPool
Repeatedly creating large byte arrays can increase GC pressure, especially during file processing, compression, or network operations. ArrayPool<T>.Shared can rent a temporary buffer and return it after use:
public static async Task CopyAsync(
Stream source,
Stream destination,
CancellationToken cancellationToken)
{
var buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
try
{
int read;
while ((read = await source.ReadAsync(buffer.AsMemory(), cancellationToken)) > 0)
{
await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}Rent may return an array larger than requested. Always write only the valid portion, represented by read. Returning the buffer in a finally block is essential. If it is not returned, pooling provides little benefit. If it is returned while another operation is still using it, data corruption and race conditions can occur. For sensitive data, consider Return(buffer, clearArray: true) according to the security requirements and the cost of clearing the buffer.
6. Disposal and ownership rules
The key question for streams, database connections, timers, and similar resources is: who owns this object? If a method creates a stream, that method will usually be responsible for disposing it. If a stream is supplied by the caller, the method should generally not dispose it unless ownership was explicitly transferred.
public async Task<byte[]> ReadFileAsync(
string path,
CancellationToken cancellationToken)
{
await using var stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: 64 * 1024,
options: FileOptions.Asynchronous | FileOptions.SequentialScan);
using var memory = new MemoryStream();
await stream.CopyToAsync(memory, cancellationToken);
return memory.ToArray();
}This example disposes resources correctly, but it still returns the complete file as a byte array. For large files, that can create substantial memory pressure. Prefer copying directly to the response stream or using a suitable FileStreamResult. Choose using or await using according to whether the resource implements IDisposable or IAsyncDisposable.
7. Measuring with dotnet-counters, dotnet-trace, and BenchmarkDotNet
Use a Release build and a repeatable workload when measuring. For first-level observation, use dotnet-counters:
dotnet-counters ps
dotnet-counters monitor --process-id 12345 --counters System.RuntimeObserve working set, heap size, total allocated bytes, and GC collections. Do not rely on a single snapshot. Look at the trend while the application processes a stable request rate.
For more detailed execution flow and CPU sampling, collect a trace with dotnet-trace:
dotnet-trace collect --process-id 12345 --duration 00:00:30Analyze the trace with an appropriate tool to investigate methods that allocate memory and hot paths that consume CPU. In production, consider the overhead, permissions, and data-handling implications of diagnostic collection.
For an isolated method comparison, use BenchmarkDotNet with MemoryDiagnoser:
[MemoryDiagnoser]
public class FormattingBenchmark
{
private readonly string[] _names = ["A", "B", "C", "D"];
[Benchmark]
public string StringBuilderVersion()
{
var builder = new StringBuilder();
foreach (var name in _names)
builder.Append(name).Append(',');
return builder.ToString();
}
}Compare allocated bytes per operation and GC information in addition to elapsed time. A microbenchmark does not guarantee the exact performance of an HTTP endpoint, but it can isolate allocation behavior and help validate an optimization hypothesis.
Common mistakes
- Using ToListAsync everywhere: It is reasonable for small results, but large queries need pagination, streaming, or another bounded strategy.
- Treating IAsyncEnumerable as unlimited streaming: Query behavior, cancellation, serializer behavior, and client support still need to be controlled.
- Failing to return pooled buffers: Return rented buffers in a
finallyblock. - Confusing capacity with valid length: A rented array may be larger than requested. Carry the number of valid bytes separately.
- Optimizing every string operation: Do not sacrifice readability for a micro-optimization that has not been measured.
- Mixing up disposal ownership: Do not close a response stream managed by the framework, and do not dispose a caller-owned stream accidentally.
- Watching memory alone: Allocation may decrease while CPU, latency, or code complexity increases. Evaluate several metrics together.
Practice exercise
- Assume that a
/reports/allendpoint loads 100,000 rows withToListAsync. - Use projection to select only the report identifier, title, and date.
- Create a second version returning
IAsyncEnumerable<ReportSummary>and pass the cancellation token through the sequence. - Run both versions under the same workload and record heap and total allocation values with
dotnet-counters. - Choose one text-formatting section and compare it with BenchmarkDotNet, including elapsed time and allocated bytes.
- Report response time, time to first item, total memory, and GC behavior rather than only one metric.
Conclusion
The purpose of memory optimization is not to eliminate every allocation. It is to remove unnecessary and uncontrolled allocations. Avoiding automatic materialization of large results, using projection, applying IAsyncEnumerable and streaming where appropriate, and reusing temporary byte buffers can provide meaningful improvements. When using ArrayPool, buffer ownership and return rules are essential. Streams and other resources must be managed according to their actual lifetime and ownership.
The most reliable workflow is to measure first, make one change, and measure the same scenario again. dotnet-counters helps you observe runtime behavior, dotnet-trace helps investigate execution paths, and BenchmarkDotNet helps isolate allocation differences. In the final lesson, we will combine these techniques and validate application performance under realistic workload conditions.
Sources
- https://learn.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1
- https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-counters
- https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-trace
- https://learn.microsoft.com/en-us/dotnet/core/diagnostics/eventpipe
- https://learn.microsoft.com/en-us/dotnet/core/compatibility/serialization/6.0/iasyncenumerable-serialization
- https://benchmarkdotnet.org/Configs/Diagnosers.htm