Repository navigation
Conversation
|
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. |
|
Tagging subscribers to this area: @dotnet/area-system-linq |
|
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)) && |
There was a problem hiding this comment.
I'm not sure I understand what the point of specializing to int or long is here, given what happens inside the specialized branch.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Other INumber can't reach this.
What prevents other INumber from reaching this?
There was a problem hiding this comment.
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.
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? |
Co-authored-by: Jan Kotas <[email protected]>
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. |
A span fast path for
Enumerable.Sum()cuts mean time by 76–95% on 32,768-elementint?,long?,float?, anddouble?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 anddoubleaccumulation forfloat?. Thedecimal?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.csand the patched file in the same checkout (0f5ee025a83).int?arraylong?arrayfloat?arraydouble?arrayfloat?listdouble?listAll four launches showed gains for the mixed arrays. The
float?singleton went from 5.35 to 5.74 ns, anddouble?from 5.64 to 5.82 ns. The 128-elementdouble?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, BenchmarkDotNet0.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
Sum<int, int>Sum<long, long>Sum<float, double>Sum<double, double>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 inlinedSum(), removed the source type checks and fallback, and shrank the caller from 136 B to 107 B. TheIEnumerable<int?>caller kept the checks.int?[]IEnumerable<int?>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
System.Linq.Testsran against the patched library. 52,256 passed, 8 skipped, 0 failed.float?widening, anddouble?accumulation order across arrays, lists, and iterators. An additional 4,440 matched-binary comparisons checked floating-point representations.git diff --checkpassed.Note
The implementation and PR description were prepared with OpenAI Codex. The performance investigation used Tedd.DotNetLab. I have manually reviewed and checked everything.