Allocation and profiling
Allocation and profiling
Allocation profiling helps locate the code that creates memory pressure; it is not the same as measuring live memory or total process memory.
A high allocation rate can increase collection work even when most objects die quickly. Retention is a separate question: roots and long-lived references keep objects alive. GC settings, server/workstation mode, heap limits and latency modes have workload-specific trade-offs; do not force GC or switch settings based only on one sample. A synchronous interval around GC.GetAllocatedBytesForCurrentThread can measure managed bytes allocated on that thread, not native bytes or surviving objects. Across await, use appropriate process-wide tooling or tracing rather than assuming thread identity. Use ArrayPool only when ownership and valid length are explicit; return once in finally and clear sensitive contents where necessary. A rented buffer can be larger than requested. Profile before replacing clear code with complex pooling. A bounded diagnostic run can compare allocation stacks, counters, throughput and latency, including serialization, database round trips and asynchronous work. Avoid real payloads and process dumps; collect only approved synthetic targets. No measured memory or speed claims are made here.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Synthetic calculations are not performance measurements.
Observe an allocation without a byte-count promise
Warm the helper before reading the thread counter; assert only that a newly allocated retained buffer increased it.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits.
using System;using System.Runtime.CompilerServices;GC.KeepAlive(Make());long before = GC.GetAllocatedBytesForCurrentThread();byte[] buffer = Make();long after = GC.GetAllocatedBytesForCurrentThread();GC.KeepAlive(buffer);Console.WriteLine(after > before ? "allocation observed" : "investigate");[MethodImpl(MethodImplOptions.NoInlining)]static byte[] Make() => new byte[4096];Expected result (not executed):
allocation observedThe exact bytes include runtime-specific overhead. The output is reasoned and not a measured counter value; repeat on the actual runtime if the assertion differs.
Use only the requested portion of a rented buffer
Keep the rental synchronous and return it even on failure.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits.
using System;using System.Buffers;byte[] rented = ArrayPool<byte>.Shared.Rent(3);try { Span<byte> data = rented.AsSpan(0, 3); data[0] = 4; data[1] = 5; data[2] = 6; int sum = 0; foreach (byte value in data) sum += value; Console.WriteLine(sum);} finally { ArrayPool<byte>.Shared.Return(rented, clearArray: true); }Expected result (not executed):
15The capacity of the rental is not the payload length. Do not access the buffer after return. Clearing trades work for data hygiene and is not a guarantee of erasing all copies.
Prioritize a fictional allocation profile
Compare modeled allocation sites using totals per second; no profiler was run.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits.
using System;var sites = new[] { (Name:"json", Bytes:120L, Calls:1000L), (Name:"format", Bytes:600L, Calls:100L), (Name:"cache", Bytes:800L, Calls:10L) };Array.Sort(sites, (a,b) => (b.Bytes*b.Calls).CompareTo(a.Bytes*a.Calls));foreach (var site in sites) Console.WriteLine($"{site.Name}: {site.Bytes*site.Calls} modeled B/s");Expected result (not executed):
json: 120000 modeled B/sformat: 60000 modeled B/scache: 8000 modeled B/sThe most expensive single call is not necessarily the largest aggregate source. Verify actual allocation stacks and user-visible outcomes before optimizing.
Apply the concept
A fictional JSON endpoint allocates 400 bytes per call at 2,000 calls/s; an audit formatter allocates 2,000 bytes at 20 calls/s. Rank them and propose a profiling plan with a correctness test.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Allocation and profiling — knowledge check
Apply the lesson concepts to the following scenarios.
What does the thread allocation counter measure?
Why slice a rented array?
When should the rental be returned?
Which site deserves initial investigation?
What is a retention question?