Repository navigation
Description
Description
PR #104815 (fixing #104512) added a pattern match in impBoxPatternMatch that eliminates boxing of ArgumentNullException.ThrowIfNull arguments in Tier-0.
The optimization fires for primitives (int, long, etc.) but not for user-defined structs — the box allocation persists indefinitely in Tier-0 and only disappears in Tier-1 when the entire call chain inlines into a hot loop and escape analysis removes the dead box.
This affects every BCL API that calls ArgumentNullException.ThrowIfNull(key) on a generic TKey (e.g. SortedList<TKey, TValue>.IndexOfKey — the original motivation in #100406) whenever TKey is a user-defined struct.
Reproduction
using System.Runtime.CompilerServices;
Test();
[MethodImpl(MethodImplOptions.NoInlining)]
static void Test()
{
for (int it = 0; it < 20; it++)
{
var a0 = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 1000; i++) Call(new MyKey(i));
var a1 = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"iter {it}: {a1 - a0} B");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void Call(MyKey k) => ArgumentNullException.ThrowIfNull(k);
readonly struct MyKey
{
public readonly int Value;
public MyKey(int value) => Value = value;
}Expected
0 B per iteration — the boxed reference is provably non-null and never escapes ThrowIfNull, so the box can be folded away regardless of the concrete value type.
This is what happens when MyKey is replaced with int (PR #104815 baseline).
Actual
iter 0: 24000 B
iter 1: 24000 B
...
iter 19: 24000 B
24 B per call (= one boxed MyKey), forever. Removing [NoInlining] from Call makes the allocation disappear after Tier-1 promotion around iteration 10, but only because the wrapper then inlines and the dead box is removed by general optimizations — not by impBoxPatternMatch itself.
Environment
- .NET SDK 10.0.200, TFM net10.0, Release, win-x64
- Default runtime config (Tiered Compilation + QuickJit + QuickJitForLoops + PGO)
Related
- Avoid boxing ArgumentNullException.ThrowIfNull arguments in Tier-0 #104512, JIT: Avoid boxing ArgumentNullException.ThrowIfNull arguments in Tier-0 #104815 — parent issue and implementing PR (tested only against
int) - SortedList allocates memory due to boxing of TKey #100406 —
SortedList<TKey, TValue>allocations with struct keys - [API Proposal]: ArgumentNullException.ThrowIfNull<T> #82227 — API proposal for a non-boxing
ArgumentNullException.ThrowIfNull<T>overload (would sidestep the JIT dependency entirely)
Activity
dotnet-policy-service commentedon May 26, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
JIT: recognize CORINFO_HELP_BOX in impThrowIfNull
JIT: recognize CORINFO_HELP_BOX in impThrowIfNull (#129392)
JIT: recognize CORINFO_HELP_BOX in impThrowIfNull (#129392)
JIT: recognize CORINFO_HELP_BOX in impThrowIfNull (dotnet#129392)