Improve Enumerable.SingleOrDefault(predicate) Logic #24058
Labels
area-System.Linq
enhancement
Product code improvement that does NOT require public API changes/additions
tenet-compatibility
Incompatibility with previous versions or .NET Framework
tenet-performance
Performance related issue
Milestone
@seanfisher commented on Sun Nov 05 2017
Improve Enumerable.SingleOrDefault logic
This improves performance for the case where more than one element is found that matches the predicate, especially in large data sets.
General
Hi, I ran across the reference source for Enumerable.cs and was surprised to see an improvement opportunity. I was about to open an issue over there but then read a closed issue where they recommended opening new issues over here instead.
In the current reference source it appears that there is needless looping over the entire enumerable even if the count of elements that match the predicate is greater than one. Here's a quick one-liner example of a short-circuit exit improvement (notice the added line right after
checked { count++; }
), although I'm sure it could be improved even further:Let me know if this is the appropriate place for this issue. It could also be that the reference source doesn't reflect exactly what the implementation is doing, because I would expect something like the Enumerable methods would have long-since been hand-tuned for performance.
@benaadams commented on Sun Nov 05 2017
It seems to be fixed in corefx?
https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Single.cs
However, for a performance improvement, you should be able to just open and Issue in the repository that has the source or open a PR change.
Although what reference source shows is the code for full framework/desktop so it could probably still do with this change (or to pick up corefx's Linq code)
@Petermarcu commented on Mon Nov 06 2017
I'm going to move this issue to corefx. The outcome here is probably to add a ref count to get this on the list of things to consider porting to .NET Framework.
The text was updated successfully, but these errors were encountered: