skip to content

An allocation profile of a C# service shows Int32 boxes from a metrics logger with object parameters and a legacy ArrayList; where else does boxing hide, and how do you remove it?

level: seniorimportance: should knowfreq 55%

answer

  1. object and interface signatures
  2. non-generic collections
  3. format strings take object
  4. members a struct only inherits
  5. keep the static type

basics

~20 s

Boxing hides wherever a value type meets an object or interface signature: ArrayList and Hashtable, object parameters, string.Format arguments, and ToString or GetHashCode on a struct that does not override them. Generic, typed APIs remove it.

solid answer

~40 s

Every conversion of a value type to `object` or an interface allocates a box, and the compiler inserts most of them silently. The usual sources: non-generic collections (`ArrayList.Add(object)`, `Hashtable.Add(object, object)`); parameters typed `object` or `params object[]`, which includes `string.Format` and home-grown logging helpers; enum values passed as `Enum`, as in `Enum.HasFlag` when the call is not fully optimized; and `ToString`, `GetHashCode` or `Equals` on a struct that inherits them from `ValueType`. The repairs keep the static type: `List<int>` and `Dictionary<TKey,TValue>`, a generic `RecordValue<T>(string, T)` overload beside the `object` one, interpolated strings (C# 10's handlers call `AppendFormatted<T>`), and overriding the inherited members on structs that are hashed or printed in hot paths.

code

csharp · 29 lines
csharp
using System.Collections;

const int Requests = 1_000;
var legacy = new ArrayList(Requests);
var modern = new List<int>(Requests);

Console.WriteLine($"ArrayList.Add:      {Measure(() => { for (int i = 0; i < Requests; i++) legacy.Add(i); })} bytes");
Console.WriteLine($"List<int>.Add:      {Measure(() => { for (int i = 0; i < Requests; i++) modern.Add(i); })} bytes");
Console.WriteLine($"Record(object):     {Measure(() => { for (int i = 0; i < Requests; i++) Metrics.Record("latency", i); })} bytes");
Console.WriteLine($"RecordValue<T>(T):  {Measure(() => { for (int i = 0; i < Requests; i++) Metrics.RecordValue("latency", i); })} bytes");

static long Measure(Action body)
{
    long before = GC.GetAllocatedBytesForCurrentThread();
    body();
    return GC.GetAllocatedBytesForCurrentThread() - before;
}

static class Metrics
{
    public static object? Last;
    public static void Record(string name, object value) => Last = value;          // every int argument is boxed
    public static void RecordValue<T>(string name, T value) => Slot<T>.Last = value;     // stored as T, no box
}

static class Slot<T>
{
    public static T? Last;
}

go deeper

for a junior

Recall that ArrayList, Hashtable and any object parameter box value types, while List<T> and Dictionary<TKey,TValue> keep them unboxed.

for a middle

Explain the quieter sites: string.Format's object arguments, Enum-typed parameters and members a struct inherits from ValueType, and what C# 10's interpolated string handlers changed.

for a senior

Walk a profile back to the signature typed object or an interface, fix it with a typed collection or a generic overload, override inherited members on hot structs, and re-measure in an optimized build.

for a principal

Decide where removing boxes pays: per-request and per-frame paths justify generic overloads and typed collections, while cold configuration code does not justify a wider API surface.

## Why boxes are easy to miss **Boxing** converts a value type to `object` or to an interface it implements, and it is implicit: no cast, no keyword, nothing in the source marks it. Each conversion allocates a small heap object, 24 bytes for an `int` in a 64-bit .NET 10 process, that dies almost at once. One box is negligible; one per value, per request, per frame becomes a steady stream of garbage that an allocation profile shows as thousands of `System.Int32` (or your struct's type) instances. The question is never "does this code box?" in the abstract but "which signature in this call chain is typed `object` or an interface?" ## The usual hiding places | Code | Why it boxes | Repair | |---|---|---| | `arrayList.Add(count)` | `ArrayList.Add` takes `object?` | `List<int>` | | `table[id] = count` on a `Hashtable` | keys and values are `object` | `Dictionary<int, int>` | | `Record("latency", ms)` with `Record(string, object)` | the parameter is `object` | a generic overload `RecordValue<T>(string, T)` | | `string.Format("{0} ms", ms)` | format arguments are `object?` | an interpolated string, `$"{ms} ms"` | | `flags.HasFlag(Perm.Read)` | the parameter is typed `Enum`, a class | `(flags & Perm.Read) != 0` | | `reading.GetHashCode()` on a struct with no override | the method that runs is `ValueType.GetHashCode`, which needs an object | override `GetHashCode`, `Equals`, `ToString` | | `IComparable<int> c = count` | interfaces are reference types | a generic method constrained to the interface | Two of these need a closer look. `Enum.HasFlag` is marked `[Intrinsic]`, and fully optimized JIT code removes both boxes; on .NET 10 it allocated 48 bytes per call in a Debug build and in a default tiered Release run of a hot loop, and none with tiered compilation disabled, so the bitwise test is the dependable form. And a struct's inherited members box because their implementation lives on `System.ValueType`, which is a class; overriding them in the struct makes the call land on the struct's own code. ## Format strings, `params` and C# 13 `string.Format` takes its arguments as `object?`, so each value-type argument is boxed. On .NET 10 a call with four `int` arguments binds to the `params ReadOnlySpan<object?>` overload that .NET 9 added, which C# 13's params collections prefer over `params object?[]`. That removes the argument array (measured: 184 bytes under C# 12, 128 under C# 14, for the same call) but each `int` is still boxed. Interpolated strings went further in C# 10: the compiler lowers `$"{ms} ms"` to a `DefaultInterpolatedStringHandler` and calls `AppendFormatted<int>(ms)`, which formats the value without boxing it. How the handler works is covered with string formatting. ## The metrics logger, measured The snippet for this question runs 1,000 adds or calls of each kind on .NET 10: - `ArrayList.Add(int)`: 24,000 bytes, one 24-byte box per value. - `List<int>.Add(int)`: 0 bytes once the list has capacity. - `Record(string, object)`: 24,000 bytes. - `RecordValue<T>(string, T)`: 0 bytes, because `T` is `int` all the way down. Keep the two overloads under different names: if both were called `Record`, a call with an `int` argument would bind to the generic overload (an exact match beats a conversion to `object`), which hides the comparison. ## Removing the boxes, in order 1. **Find the signature.** Follow the boxed type in the profile to the call that converts it; the culprit is the first parameter, field or collection typed `object`, `Enum` or an interface. 2. **Keep the static type.** Swap non-generic collections for `List<T>`, `Dictionary<TKey,TValue>` and `HashSet<T>`; add a generic overload beside an `object` parameter; prefer interpolated strings to `string.Format` in hot paths. 3. **Override inherited members** on structs that are hashed, compared or printed often. 4. **Re-measure in an optimized build.** The JIT removes some boxes (the `HasFlag` case) only in fully optimized code, so a Debug measurement can overstate them. ## What is not worth chasing - Boxing in code that runs once (startup, configuration parsing) costs nothing measurable. - An `object` overload kept for flexibility is fine when hot callers use a generic one. - Some boxes are the point: storing values of different types in one `object` slot is what boxing exists for. The aim is to stop paying for boxes nobody needed.

  • Does the interpolated string $"{ms} ms" box ms the way string.Format("{0} ms", ms) does?
    No, from C# 10 on .NET 6 or later. The compiler lowers the interpolated string to a `DefaultInterpolatedStringHandler` and calls `AppendFormatted<int>(ms)`, which formats without converting to `object`. `string.Format` takes `object?` arguments, so the `int` is boxed: on .NET 10, a one-argument call allocated 72 bytes against 48 for the interpolated version, the difference being one 24-byte box.
  • Why does calling GetHashCode() on a struct local box it when the struct does not override the method?
    The implementation that runs is `ValueType.GetHashCode`, an instance method of `System.ValueType`, which is a class. To call it the runtime needs an object reference as the receiver, so it boxes the struct first. Overriding `GetHashCode` in the struct makes the call reach the struct's own method with no box; measured on .NET 10, 24 bytes per call without the override and 0 with it.
  • Is Enum.HasFlag still a boxing trap on .NET 10?
    Sometimes. Its signature is `HasFlag(Enum flag)`, so the receiver and the argument are both converted to the class `Enum`. The method is marked `[Intrinsic]` and fully optimized JIT code removes both boxes, but on .NET 10 it allocated 48 bytes per call in a Debug build and in a default tiered Release run of a hot loop, and none with tiered compilation disabled. `(flags & Perm.Read) != 0` never boxes.

  • Generic collections box too, so List<int> is no better than ArrayList.
  • Calling ToString or GetHashCode on a struct never boxes because the call is made on a value.
  • Interpolated strings box every value-type hole just like string.Format.
  • C# 13 params spans made string.Format allocation-free for value-type arguments.
  • Boxing only costs CPU time; it creates no garbage.

Assumes C# 14 on .NET 10: string.Format binds to the params ReadOnlySpan<object?> overload added in .NET 9, which removes the argument array but still boxes each value-type argument.