Generations and allocation measurement
Generations and allocation measurement
The managed collector groups objects into generations, normally 0, 1 and 2. Most small objects start in generation 0; surviving collections may promote them. Large objects typically enter the large object heap, collected with generation 2. Allocation rate, retained heap, collection count and pause duration answer different performance questions. Measure them separately instead of inferring memory use from a single number.
Proposed baseline: .NET 10 / C# 14 (SDK 10.0.404 inherited). Ordinary CoreCLR SDK console build, not Native AOT. No additional packages. Outputs are reasoned, not executed.
Inspect the valid generation range
Do not predict the exact generation of an object after intervening runtime work.
using System;var sample = new byte[128];int generation = GC.GetGeneration(sample);Console.WriteLine(generation >= 0 && generation <= GC.MaxGeneration);GC.KeepAlive(sample);GetGeneration reports the current generation, not how long an object has existed. The assertion checks only a valid range.
Expected observation (reasoned, not executed):
TrueMeasure allocation without printing variable byte counts
Run one small allocation on the current thread. The counter is cumulative, so take a delta.
using System;_ = GC.GetAllocatedBytesForCurrentThread();long before = GC.GetAllocatedBytesForCurrentThread();var bytes = new byte[1024];bytes[0] = 7;long delta = GC.GetAllocatedBytesForCurrentThread() - before;GC.KeepAlive(bytes);Console.WriteLine(delta >= 1024);Console.WriteLine(bytes[0]);The array allocation should be reflected in the current-thread counter on the selected CoreCLR build. The exact byte count includes runtime object layout and possible other allocations. This is a reasoned observation, not a measured benchmark.
Expected observation (reasoned, not executed):
True7Compare equivalent string workloads
Warm up both paths and check the same output before interpreting allocation deltas. Print only functional equivalence; the two counters are available for inspection in a debugger.
using System;using System.Text;static string Repeated(int n) { string text = ""; for (int i = 0; i < n; i++) text += "x"; return text; }static string Builder(int n) { var text = new StringBuilder(n); for (int i = 0; i < n; i++) text.Append('x'); return text.ToString(); }_ = Repeated(32); _ = Builder(32);long start = GC.GetAllocatedBytesForCurrentThread();string a = Repeated(64);long repeatedBytes = GC.GetAllocatedBytesForCurrentThread() - start;start = GC.GetAllocatedBytesForCurrentThread();string b = Builder(64);long builderBytes = GC.GetAllocatedBytesForCurrentThread() - start;Console.WriteLine(a == b);Console.WriteLine(a.Length);Repeated concatenation can create intermediate strings, whereas StringBuilder can reuse a buffer. Warm-up reduces some noise but does not establish a statistically meaningful benchmark. Inspect repeatedBytes and builderBytes without claiming a particular ordering or magnitude for every runtime.
Expected observation (reasoned, not executed):
True64Common mistakes and edge cases
Current-thread allocation counters include allocations that were already reclaimed and exclude other threads and unmanaged memory. Do not use them across awaits that can resume on another thread. CollectionCount counts collections rather than allocation bytes; higher generation collections also collect younger generations. The common LOH threshold is around 85,000 bytes of total object size by default, not an array element count and not a universal configuration guarantee. Use representative Release builds, repeated samples and a profiler before optimizing; avoid GC.Collect as a routine performance fix.
Practice and recap
Design a measurement comparing construction of 128 and 512 characters with repeated concatenation and StringBuilder. Specify what to record and what conclusion is not justified.
Hint: Verify identical outputs.
Learning objective: Identify a meaningful allocation experiment. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generations and allocation measurement — knowledge check
Apply the lesson concepts to the following scenarios.
Which generation commonly receives small new objects?
What does allocation delta measure?
Why warm up both paths?
What does equal output establish?
What is the usual large-object threshold based on?