I am writing a Mesh Rendering manager and thought it would be a good idea to group all of the meshes which use the same shader and then render these while I'm in that shader pass.
I am currently using a foreach
loop, but wondered if utilising LINQ might give me a performance increase?
I think LINQ is better to use over a
foreach
loop, because it gives you much cleaner and easy-to-understand code. But LINQ is slower thanforeach
. To get more, go through the article LINQ vs FOREACH vs FOR Loop Performance.Why should LINQ be faster? It also uses loops internally.
Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code.
It should probably be noted that the
for
loop is faster than theforeach
. So for the original post, if you are worried about performance on a critical component like a renderer, use afor
loop.Reference: In .NET, which loop runs faster, 'for' or 'foreach'?
You might get a performance boost if you use parallel LINQ for multi cores. See Parallel LINQ (PLINQ) (MSDN).
LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc. In most code this will be virtually undetectable, and more than afforded by the simpler to understand code.
With other LINQ providers like LINQ-to-SQL, then since the query can filter at the server it should be much better than a flat
foreach
, but most likely you wouldn't have done a blanket"select * from foo"
anyway, so that isn't necessarily a fair comparison.Re PLINQ; parallelism may reduce the elapsed time, but the total CPU time will usually increase a little due to the overheads of thread management etc.
This is actually quite a complex question. Linq makes certain things very easy to do, that if you implement them yourself, you might stumble over (e.g. linq .Except()). This particularly applies to PLinq, and especially to parallel aggregation as implemented by PLinq.
In general, for identical code, linq will be slower, because of the overhead of delegate invocation.
If, however, you are processing a large array of data, and applying relatively simple calculations to the elements, you will get a huge performance increase if:
You use a for loop to access each element (as opposed to foreach or linq).