For vs. Linq - Performance vs. Future
c#, linq, performance
Solution
The best practice depends on what you need:
- Development speed and maintainability: LINQ
- Performance (according to profiling tools): manual code
LINQ really does slow things down with all the indirection. Don't worry about it as 99% of your code does not impact end user performance.
I started with C++ and really learnt how to optimize a piece of code. LINQ is not suited to get the most out of your CPU. So if you measure a LINQ query to be a problem just ditch it. But only then.
For your code sample I'd estimate a 3x slowdown. The allocations (and subsequent GC!) and indirections through the lambdas really hurt.
Problem
Very brief question. I have a randomly sorted large string array (100K+ entries) where I want to find the first occurance of a desired string. I have two solutions. From having read what I can my guess is that the 'for loop' is going to currently give slightly better performance (but this margin could always change), but I also find the linq version much more readable. On balance which method is generally considered current best coding practice and why? ``` string matchString = "dsf897sdf78"; int matchIndex = -1; for(int i=0; i<array.length; i++) { if(array[i]==matchString) { matchIndex = i; break; } } ``` or ``` int matchIndex = array.Select((r, i) => new { value = r, index = i }) .Where(t => t.value == matchString) .Select(s => s.index).First(); ```