Skip to content

Optimize nullable LINQ Sum for arrays and lists - #137689

Open
tedd wants to merge 3 commits into
dotnet:mainfrom
tedd:codex/nullable-integral-linq-sum-upstream
Open

tedd wants to merge 3 commits into
dotnet:mainfrom
tedd:codex/nullable-integral-linq-sum-upstream

Conversation

@tedd

@tedd tedd commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

A span fast path for Enumerable.Sum() cuts mean time by 76–95% on 32,768-element int?, long?, float?, and double? arrays with about 50% nulls.

Arrays and List<T> use the span loop. Adding zero for nulls removes the per-element null check while preserving checked integer overflow order and double accumulation for float?. The decimal? overload continues to skip nulls. In a separate source-copy benchmark, adding zero for each null made a 90%-null decimal array 7.6× slower.

Shared benchmark coverage is in dotnet/performance#5366.

BenchmarkDotNet

Selected means from matched Release builds. Each call sums 32,768 preallocated values with about 50% nulls and consumes the result. The comparison uses the original upstream Sum.cs and the patched file in the same checkout (0f5ee025a83).

Case Baseline Patched Time reduction
int? array 148.27 µs 10.40 µs 93.0%
long? array 203.12 µs 10.78 µs 94.7%
float? array 123.34 µs 29.32 µs 76.2%
double? array 204.48 µs 29.44 µs 85.6%
float? list 87.33 µs 29.39 µs 66.4%
double? list 94.52 µs 29.47 µs 68.8%

All four launches showed gains for the mixed arrays. The float? singleton went from 5.35 to 5.74 ns, and double? from 5.64 to 5.82 ns. The 128-element double? iterator went from 292.76 to 317.51 ns in the main run, with one patched launch at 374.93 ns. A separate six-launch repeat measured 293.24 and 295.22 ns with overlapping confidence intervals. Decimal controls were within 1%, and all measured cases allocated 0 B/op.

Ryzen 9 5950X, Windows x64, .NET 12.0.0-alpha.1.26557.102, concurrent workstation GC, BenchmarkDotNet 0.16.0-preview.2. Four fresh processes per arm and case, with five warmups and twelve 150 ms measurement iterations configured per process.

x64 code size

Optimized JIT helper (FullOpts) Baseline Patched
Sum<int, int> 179 B 286 B
Sum<long, long> 188 B 290 B
Sum<float, double> 199 B 298 B
Sum<double, double> 194 B 293 B

The public wrappers remain 6 B. The span loops have no per-element bounds or null checks.

Direct singleton calls

The direct int?[] call was faster in both launches. Tier 1 x64 inlined Sum(), removed the source type checks and fallback, and shrank the caller from 136 B to 107 B. The IEnumerable<int?> caller kept the checks.

One-element array call Baseline (ns) Patched (ns)
Direct int?[] 4.61, 4.82 3.77, 3.60
Through IEnumerable<int?> 4.93, 5.25 5.30, 4.97

Earlier integer-only comparison on the same runtime. The delegate-based singleton benchmark for that revision measured 4.99 → 5.37 ns. BenchmarkDotNet used four fresh processes in baseline–patched–patched–baseline order. Confidence intervals overlapped. Both paths allocated 0 B/op.

Validation

  • Release System.Linq.Tests ran against the patched library. 52,256 passed, 8 skipped, 0 failed.
  • Regression tests cover checked intermediate integer overflow, float? widening, and double? accumulation order across arrays, lists, and iterators. An additional 4,440 matched-binary comparisons checked floating-point representations.
  • git diff --check passed.

Note

The implementation and PR description were prepared with OpenAI Codex. The performance investigation used Tedd.DotNetLab. I have manually reviewed and checked everything.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 16, 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-linq
See info in area-owners.md if you want to be subscribed.

@jkotas

jkotas commented Nov 16, 2026

Copy link
Copy Markdown
Member

Do you have evidence that the scenario that this is trying to optimize is sufficiently common in the code out there?

@tedd

tedd commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Do you have evidence that the scenario that this is trying to optimize is sufficiently common in the code out there?

I do not. What sort of evidence is required / how would I find such evidence? (I'm new to pushing PR's for dotnet runtime, so trying to learn.)

The optimization is substantial for nullable int/long - typically in datasets received from a database / financial API endpoints. The only regression is for very small collections (single numbers), where the timing is in µs. So I considered it an acceptable trade-off.


TAccumulator sum = TAccumulator.Zero;
foreach (TSource? value in source)
if ((typeof(TSource) == typeof(int) || typeof(TSource) == typeof(long)) &&

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand what the point of specializing to int or long is here, given what happens inside the specialized branch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, tested it now. I made an incorrect assumption on cost of the branch vs float. I see considerable regression on decimal, but float/double benefits from the optimization. Other INumber can't reach this. I'll update PR and run benchmark again.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Other INumber can't reach this.

What prevents other INumber from reaching this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What prevents other INumber from reaching this?

The containing generic method is private and there is no public overload for Sum() other than int, long, float, double and decimal.

@tedd tedd changed the title Optimize nullable integral LINQ Sum for arrays and lists Optimize nullable LINQ Sum for arrays and lists Nov 17, 2026
@jkotas

jkotas commented Nov 17, 2026

Copy link
Copy Markdown
Member

The optimization is substantial for nullable int/long - typically in datasets received from a database / financial API endpoints.

Have you encountered this in your own project? What kind of difference it made?

@eiriktsarpalis

Copy link
Copy Markdown
Member

The optimization is substantial for nullable int/long - typically in datasets received from a database / financial API endpoints.

Have you encountered this in your own project? What kind of difference it made?

In such cases the enumerable is almost never backed by a single span. How would this optimization help?

@tedd

tedd commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

The optimization is substantial for nullable int/long - typically in datasets received from a database / financial API endpoints.

Have you encountered this in your own project? What kind of difference it made?

We have a custom built integration engine running large quantities of data from ERP/operational systems. Many of these vendors consistently use nullable data types. We do much of our processing in C# rather than complex SP's that is difficult to maintain. This ranges from ELT with upserts to period aggregation and statistical preprocessing.

We also have a custom SQL engine wrapping all our data sources. If the underlying data source does not support aggregation or the operation crosses datasets (join / subquery), then our engine fetch the data and processes it directly in memory. A dataset in our context is different databases / files, but also different schemas within same db. We've had to limit the internal engine aggregation at 20K rows due to resource usage, above that an query must be reshaped.

I haven't measured what overall difference this makes though.

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.Linq 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.

3 participants