对于与LINQ的 - 性能与未来 [英] For vs. Linq - Performance vs. Future

查看:78
本文介绍了对于与LINQ的 - 性能与未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单的问题。我有一个随机排序的大字符串数组(100K +的条目),我想找到一个所需的字符串中第一次出现。我有两个解决方案。

这在阅读我能我的猜测是什么样的循环将会给目前表现略好(但利润率可能会随时改变),但我也觉得LINQ的版本更具有可读性。在平衡这些方法通常被认为是目前最好的编码实践,为什么?

 字符串matchString =dsf897sdf78;
INT matchIndex = -1;
的for(int i = 0; I< array.length,我++)
{
    如果(阵列[我] == matchString)
    {
        matchIndex = I;
        打破;
    }
}

  INT matchIndex = array.Select((R,I)=>新建{值= R,指数= I})
                         。凡(T => t.value == matchString)
                         。选择(S = GT; s.index)。首先();


解决方案

最好的方法取决于你所需要的:


  1. 发展速度和可维护性:LINQ

  2. (根据分析工具)性能:手动code

LINQ确实放慢改革的步伐与所有的间接。不要担心它作为你的code的99%,不影响最终用户的性能。

我开始用C ++,真正学会了如何优化一块code的。 LINQ不适应充分利用你的CPU。所以,如果你衡量一个LINQ查询是一个问题,只是把它扔。但才到。

有关您的code样品我估计3倍放缓。通过lambda表达式的分配(以及随后的GC!),并迂回真的受伤了。

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();

解决方案

The best practice depends on what you need:

  1. Development speed and maintainability: LINQ
  2. 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.

这篇关于对于与LINQ的 - 性能与未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆