Repository navigation
Description
I'm using extension GetEnumerator (coming in C# 9) to implement foreach on Range. See https://github.com/YairHalberstadt/RangeForeach.
I'm using sharplab to check the jit output.
I want everybody to be able to rewrite their for loops to foreach loops without having to think about any potential performance impact. Therefore ideally we'd want M1 and M2 in:
public static class Program {
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void M1() {
foreach (var i in 1..10)
Console.WriteLine(i);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void M2() {
for (int i = 1; i<10; i++)
Console.WriteLine(i);
}
}To have identical asm.
My current implementation is:
using System;
using System.Runtime.CompilerServices;
public static class Program {
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void M1() {
foreach (var i in 1..10)
Console.WriteLine(i);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void M2() {
for (int i = 1; i<10; i++)
Console.WriteLine(i);
}
}
public static class RangeExtensions
{
public struct RangeEnumerator
{
public RangeEnumerator(int start, int end) => (Current, _end) = (start - 1, end);
public int Current { get; private set; }
private int _end;
public bool MoveNext() => ++Current < _end;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RangeEnumerator GetEnumerator(this Range range)
{
if (range.Start.IsFromEnd || range.End.IsFromEnd)
ThrowIsFromEnd();
if (range.Start.Value > range.End.Value)
ThrowStartIsGreaterThanEnd();
return new RangeEnumerator(range.Start.Value, range.End.Value);
static void ThrowIsFromEnd() => throw new ArgumentException("range start and end must not be from end");
static void ThrowStartIsGreaterThanEnd() => throw new ArgumentException("start is greater than end");
}
}Jit is:
Program.M1()
L0000: push ebp
L0001: mov ebp, esp
L0003: push edi
L0004: push esi
L0005: mov ecx, 1
L000a: mov eax, 0xa
L000f: cmp ecx, eax
L0011: jg short L0030
L0013: mov esi, 1
L0018: mov edi, 0xa
L001d: dec esi
L001e: jmp short L0027
L0020: mov ecx, esi
L0022: call System.Console.WriteLine(Int32)
L0027: inc esi
L0028: cmp esi, edi
L002a: jl short L0020
L002c: pop esi
L002d: pop edi
L002e: pop ebp
L002f: ret
L0030: call dword ptr [0x2622c9fc]
L0036: int3
Program.M2()
L0000: push ebp
L0001: mov ebp, esp
L0003: push esi
L0004: mov esi, 1
L0009: mov ecx, esi
L000b: call System.Console.WriteLine(Int32)
L0010: inc esi
L0011: cmp esi, 0xa
L0014: jl short L0009
L0016: pop esi
L0017: pop ebp
L0018: retTo be honest I'm pretty impressed by how much the JIT is managing to do here, but it's still approximately twice as long.
The main thing that isn't getting optimized away is the if (range.Start.Value > range.End.Value) check.
Any ideas if I can optimize this further, or if the JIT might be able to do better here?
category:cq
theme:optimization
skill-level:expert
cost:large
Activity
[-]Help with improving JIT for method[/-][+]Help with improving JIT for Range GetEnumerator[/+]SingleAccretion commentedon Aug 13, 2020
It appears you are using x86 JIT. That said, x64 code with my recent-ish version of the runtime, obtained via Disasmo, is not substantially different:
I was able to make the comparison go away with this hack, but I do not know if it is good enough in the general case:
AndyAyersMS commentedon Aug 13, 2020
Thanks for the report. #11848 called out a number of issues with the performance of
Range. Good news is that most of these have been addressed over time, but it looks like there's more to do.Marking as future since we're closing down work for 5.0
cc @dotnet/jit-contrib
YairHalberstadt commentedon Aug 13, 2020
That's great @AndyAyersMS
When we remove all usage of range, and just pass in the start and end directly:
X86 does a pretty good job:
x64 meanwhile is still not great:
SingleAccretion commentedon Aug 13, 2020
This is not the codegen I am getting. I too saw it on sharplab and was a bit puzzled. But it does indeed seem like .NET 5 is that much better than .NET Core 3.1 in this case.
AndyAyersMS commentedon Mar 30, 2021
@YairHalberstadt have you had a chance to look at 5.0 (or even 6.0) codegen here? For the second example I am seeing:
Actually using range here still has challenges -- when we eliminate upstream control flow in assertion prop we don't clean up downstream dead phis, and so fail to propagate constants. LSRA then manages to preference and coalesce a bunch of temp lifetimes and the final codegen has obvious known-outcome compares that don't get optimized, as in the example shown above by @SingleAccretion
AndyAyersMS commentedon Apr 9, 2021
Ok, I am going to mark this as future.
There is still the interesting case where we clean up control flow during optimization and then fail to benefit from that like we should. We see this a lot with index and range.
AndyAyersMS commentedon Jun 5, 2026
Note
AI-assisted (Copilot CLI).
Re-checked on current
main(arm64). Substantial improvement since 2021 (codegen ~60 B for the variable-N variant vs. ~150+ B then), but the foreach-over-Range form is still ~2× slower than the equivalentforloop. Root cause is now isolated and there is a small one-line codegen tweak that recovers ~25% of the gap by itself.Numbers (Apple M4 Max, arm64,
DOTNET_TieredCompilation=0, N=100, 5 M outer iterations)for (int i = 1; i < n; i++)foreach (...)over enumerator with plainint Currentfieldforeach (...)over enumerator withint Current { get; private set; }The plain-field variant produces identical codegen to the for loop. The auto-property version is the slow one.
Root cause in the JIT
Slow inner loop:
The auto-property
private setinlines asSTOREIND(LCL_ADDR(struct), value). After struct promotion, the destination is the promoted<Current>k__BackingField(TYP_INT) and the IR contains noCASTnode — yet arm64 codegen still emitssxtwfor the int-to-int register move. Trace:genCodeForStoreLclVar→inst_Mov_Extend(targetType=TYP_INT, ...)ins_Move_Extend(TYP_INT, srcInReg=true)insrc/coreclr/jit/instr.cpp:2008-2011returnsINS_sxtwforsrcType == TYP_INT.For a TYP_INT-to-TYP_INT reg-reg move on arm64,
INS_mov(encoded asorr Wd, WZR, Wn) is sufficient: subsequent 32-bit ops ignore upper bits, and any genuine int→long widening has an explicitCASTin the IR that takes a different codegen path.Local patch + measurement
Single-line change:
Rebuilt checked arm64 JIT, swapped into Core_Root, re-measured:
Quick sanity for sign-extension preservation:
(long)int.MinValue,Neg(int.MinValue), etc. all still produce correct results (the explicitCASTpath is unaffected).The remaining ~12 ns gap from M2 is from V06 / V07 not being register-coalesced (an extra
mov w3, w2per iteration). That is a separate, longstanding LSRA limitation.Suggestion
The
sxtw → movchange is a clean isolated improvement and likely useful across many int-heavy arm64 inner loops; I will open a focused issue for it and link back here.ins_Move_Extendis called from several sites (codegenarm64.cpp:3020,codegencommon.cpp:7227,hwintrinsiccodegenarm64.cpp), so the other callers should be reviewed before the change is more than a proof of concept. SPMI diff would confirm broader impact.AndyAyersMS commentedon Jun 5, 2026
Filed the focused JIT codegen issue as #129052.
AndyAyersMS commentedon Jun 7, 2026
Think we can close this one now.