Skip to content

Use the span fast path in Enumerable.Average with a selector - #138044

Open
ketanvijayvargiya wants to merge 1 commit into
dotnet:mainfrom
ketanvijayvargiya:linq-average-selector-span
Open

ketanvijayvargiya wants to merge 1 commit into
dotnet:mainfrom
ketanvijayvargiya:linq-average-selector-span

Conversation

@ketanvijayvargiya

@ketanvijayvargiya ketanvijayvargiya commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Average(source, selector) enumerates arrays and List<T> through IEnumerable<T>. Count(predicate), Any, All, First and Aggregate already use TryGetSpan for those; this does the same for the Average overloads that take a selector. Each of the two private helpers they forward to becomes a dispatcher, a span loop, and the existing loop moved into its own method without changes.

Two details in the span loops:

  • The sum starts from the first selected value, as the existing loops do, and not from zero. That keeps results identical to the bit, including an average of negative zeros.
  • The nullable loop is a single loop with a count == 0 check. I first wrote it like the existing one (a loop that finds the first value, then a loop for the rest), but for decimal? the JIT then copied the selected value to the stack with two stores and read it back across both, and a one-item array went from 13.1 ns to 16.8 ns. With the single loop the value stays in registers and that case is 8.7 ns.

Numbers

BenchmarkDotNet, each case in its own process. "Before" is Average.cs from main. Times in ns. The source holds reference-type items and the selector reads a field.

Items Source int double decimal int? double? decimal?
1 Array 5.47 → 1.26 5.69 → 1.29 13.66 → 8.56 6.41 → 2.25 5.97 → 2.09 13.08 → 8.66
1 List 7.77 → 1.46 7.76 → 1.28 14.47 → 8.06 7.91 → 2.37 7.38 → 2.15 15.50 → 7.78
1 Where 8.46 → 12.44 8.62 → 10.09 16.44 → 16.36 9.06 → 12.71 8.93 → 8.40 16.60 → 16.88
10 Array 10.71 → 4.50 10.30 → 3.33 46.28 → 37.02 16.09 → 8.27 13.64 → 7.35 53.54 → 42.14
10 List 16.35 → 5.11 17.55 → 3.95 57.58 → 39.11 25.38 → 8.98 20.22 → 8.73 68.65 → 43.92
10 Where 20.93 → 20.92 21.01 → 21.16 65.08 → 63.77 26.41 → 25.79 24.54 → 25.05 67.78 → 68.74
1,000 Array 948 → 525 870 → 610 3,735 → 3,283 1,435 → 788 1,304 → 743 2,887 → 2,304
1,000 List 1,742 → 518 1,661 → 614 4,624 → 3,309 1,896 → 800 1,842 → 691 3,763 → 2,340
1,000 Where 1,758 → 1,412 1,326 → 1,344 4,829 → 5,058 1,784 → 1,802 1,791 → 1,839 3,691 → 3,646

Arrays and lists are faster in every cell: 1.4x to 6.1x for int, double and their nullable forms, 1.1x to 2.0x for decimal and decimal?.

Other sources run the same loop as before, after one extra type check. That costs 1 to 4 ns per call, which shows only on a single item; from 10 items they are level within run-to-run noise.

I do not have a full local build of the runtime. I compiled Average.cs from main and from this branch side by side into one console app (.NET SDK 10.0.403, x64, Windows 11). I can ask EgorBot for numbers on main if preferred.

Code size

Fully optimized code for one selector type with a reference-type source, helper before against dispatcher + span loop + enumerable loop after, in bytes:

int double decimal int? double? decimal?
Before 400 385 583 485 454 643
After 746 719 1,062 877 835 1,244

Behavior

Results, exceptions and argument checks are unchanged. As with the other span paths, a selector that modifies the List<T> being averaged no longer gets an InvalidOperationException.

Tests

Three tests added to AverageTests, running every selector overload over every source shape from CreateSources: the averages (with a leading item that has no value for the nullable overloads), sources with no values, and overflow. They also pass with Average.cs from main.

With the side-by-side app I compared the branch against main for all ten overloads over an array, a List<T> and an iterator on random inputs, including empty sources, nulls, overflow, NaN, infinities and negative zero for double, float and decimal: 1,200,000 comparisons, the same bits or the same exception type every time.

I compiled the System.Linq sources from this branch into a standalone .NET 10 project and ran AverageTests.cs against them: 298 pass. I have not run the full System.Linq suite against a built runtime locally, so I am relying on CI for that.

Average(source, selector) enumerates arrays and List<T> through IEnumerable<T>. Use TryGetSpan for those, as the other span paths do. Each of the two private helpers becomes a dispatcher plus one method per loop.
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 20, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Collections community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant