使用LINQ&QUOT时,性能的关注;处处"? [英] Performance concern when using LINQ "everywhere"?

查看:228
本文介绍了使用LINQ&QUOT时,性能的关注;处处"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

升级到ReSharper5后,它给了我即使是在code改进更多有用的技巧。我一看,现在到处是一个提示,以取代的​​foreach语句使用LINQ查询。拿这个例子:

After upgrading to ReSharper5 it gives me even more useful tips on code improvements. One I see everywhere now is a tip to replace foreach-statements with LINQ queries. Take this example:

private Ninja FindNinjaById(int ninjaId)
{
    foreach (var ninja in Ninjas)
    {
        if (ninja.Id == ninjaId)
            return ninja;
    }
    return null;
}

此建议替换为以下使用LINQ:

This is suggested replaced with the following using LINQ:

private Ninja FindNinjaById(int ninjaId)
{
    return Ninjas.FirstOrDefault(ninja => ninja.Id == ninjaId);
}

这看起来都很好,我敢肯定,这是没有问题方面的性能来代替这一个的foreach。但是,它是我应该做的有什么看法?或者,也许我遇到所有这些LINQ查询随处可见的性能问题?

This looks all fine, and I'm sure it's no problem regarding performance to replace this one foreach. But is it something I should do in general? Or might I run into performance problems with all these LINQ queries everywhere?

推荐答案

您需要了解的LINQ查询会做引擎盖下和比较,来运行你的code之前,你可以知道你是否应该改变它。一般情况下,我的意思不是说你需要知道将要发生的确切code,但你需要知道它会如何去执行操作的基本思路。在你的榜样,我会猜测,LINQ将基本工作大致相同的code和因为LINQ语句更加紧凑和描述,我想preFER它。有很多次,不过,当LINQ未必是理想的选择,虽然可能不是很多。一般来说,我会认为几乎所有的循环结构将更换由具有同等LINQ结构。

You need to understand what the LINQ query is going to do "under the hood" and compare that to running your code before you can know whether you should change it. Generally, I don't mean that you need to know the exact code that will be generated, but you do need to know the basic idea of how it would go about performing the operation. In your example, I would surmise that LINQ would basically work about the same as your code and because the LINQ statement is more compact and descriptive, I would prefer it. There are times, though, when LINQ may not be the ideal choice, though probably not many. Generally I would think that just about any looping construct would be replaceable by an equivalent LINQ construct.

这篇关于使用LINQ&QUOT时,性能的关注;处处"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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