For vs. Linq - 性能 vs. 未来 [英] For vs. Linq - Performance vs. Future
问题描述
非常简短的问题.我有一个随机排序的大字符串数组(100K+ 个条目),我想在其中找到所需字符串的第一次出现.我有两个解决方案.
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.
通过阅读我可以猜测的是,for 循环"目前的性能会稍好一些(但这个边距总是会改变),但我也发现 linq 版本更具可读性.总的来说,哪种方法通常被认为是当前的最佳编码实践,为什么?
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;
}
}
或
int matchIndex = array.Select((r, i) => new { value = r, index = i })
.Where(t => t.value == matchString)
.Select(s => s.index).First();
推荐答案
最佳实践取决于您的需求:
The best practice depends on what you need:
- 开发速度和可维护性:LINQ
- 性能(根据分析工具):手动代码
LINQ 确实通过所有间接方式减慢了速度.不要担心,因为 99% 的代码不会影响最终用户的性能.
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.
我从 C++ 开始,真正学会了如何优化一段代码.LINQ 不适合充分利用您的 CPU.因此,如果您认为 LINQ 查询是一个问题,请放弃它.但只有这样.
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.
对于您的代码示例,我估计速度会降低 3 倍.通过 lambda 进行的分配(以及随后的 GC!)和间接访问真的很伤人.
For your code sample I'd estimate a 3x slowdown. The allocations (and subsequent GC!) and indirections through the lambdas really hurt.
这篇关于For vs. Linq - 性能 vs. 未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!