-
Notifications
You must be signed in to change notification settings - Fork 817
Array/Seq.Average and similar functions do not use foreach #885
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I think @dsyme already said that such PRs are welcome. |
@forki I will be glad to fix this when I learn how to build this repo on my old MacBookAir :) A year ago I couldn't. BTW, I have tested LINQ .Average() and F# |
Given that I have reverted my pull request regarding |
OK, thanks Just to mention that it may be possible to get some generic doing struct-enumerator iteration using statically resolved type variables, e.g. see below. This technique doesn't easily generalize to map, collect etc. but may be enough for your purposes
|
Thanks! That is very interesting. I thought about generics with type constraints that will allow to use constrained call for structs. But both approaches require knowing the type at compile time. |
Here F# always gets an enumerator and uses it to iterate over a sequence. This throws away compiler optimizations for
foreach
loop.In this example calculating average of double array generates the largest amount of allocations via
.GetEnumerator()
. It was surprising to find it here.LINQ uses
foreach
which eliminates allocations. As the linked SO question indicates, F# compiler supports the sameforeach
optimization as C# compiler and.GetEnumerator()
calls should be eliminated where possible in favor offoreach
.For Arrays it is better to use
for..
loop because Arrays do not have a struct enumerator as shown here. Onlyfor..
loop like here completely eliminates allocations and this would be nice to have in the core library.The text was updated successfully, but these errors were encountered: