Whenever I tried to find actual data for this Linq seemed to be slightly slower, but not too much.
Examples: https://codereview.stackexchange.com/questions/14197/is-the-... https://wheresmykeyboard.com/2015/06/linq-lambda-loop-perfor...
Whenever I tried to find actual data for this Linq seemed to be slightly slower, but not too much.
Examples: https://codereview.stackexchange.com/questions/14197/is-the-... https://wheresmykeyboard.com/2015/06/linq-lambda-loop-perfor...
But something like:
var sum = values.Sum(x => x * x);
will take ~10x longer than an for or foreach loop equivalent.(260ms vs 36ms on 32 million float32s on my machine, measured by benchmarkdotnet)
plus a small allocation
I made some benchmarks myself: 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-obv... I should have read that earlier!
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.For anyone that needs maximum performance then they should clearly be wary of anything that requires invocation of lambdas, but the usefulness of Linq shouldn't be written off because of that - the declarative style leads to fewer bugs, more stable, maintainable and easier to read code - that in itself is a performance boost.