3 ms·
Thanks for your reply. I'm fairly new to C#, and was hoping that linq would make my life easier. Oh well. I made some benchmarks myself: https://pastebin.com/5
by roetlich 7y ago
Thanks for your reply. I'm fairly new to C#, and was hoping that linq would make my life easier. Oh well.
I made some benchmarks myself: https://pastebin.com/5vQNpbPC https://pastebin.com/5vQNpbPC
And esp. the Sum is a lot slower in linq. Not quite an order of magnitude, but pretty bad.
Even worse:
float sum = 0;
arr.Select(x => (sum += x * x)).ToList();
return sum;
This is somehow still a lot faster than the normal linq Sum. What does .Sum() do to be this slow?
Edit: I just noticed you also wrote this blog post on the topic:
https://jackmott.github.io/programming/2016/07/22/making-obvious-fast.html https://jackmott.github.io/programming/2016/07/22/making-obv...
I should have read that earlier!
- louthy 7y agoYou're doing more work though. You're converting to a List<T> (in order to caox the lazy enumerable to enumerate). You should use Aggregate for a more (generalised) way to reduce/fold collections into a value: var sum = arr.Aggregate(0, (t, x) => t + (x * x)); On the whole though it's better to use Linq until it's not. It's more declarative which will lead to more reliable code. Optimise when you find performance issues, don't write bad code just because you may gain a few nanoseconds here and there.