C#LINQ首先()比ToArray的(更快)[0]? [英] C# LINQ First() faster than ToArray()[0]?
问题描述
我正在运行测试
它看起来像:
方法1)
列表< INT> =新的List< INT> {1,2,4,...} //假设1000K
VAR结果ErrorCodes.Where(X => ReturnedErrorCodes.Contains(X))一()。
方法2)
列表与LT; INT> =新的List< INT> {1,2,4,...} //假设1000K
VAR的结果= ErrorCodes.Where(X => ReturnedErrorCodes.Contains(X))。ToArray的() 0];
为什么相比于方法1?
方法2是如此之慢< DIV CLASS =h2_lin>解决方案
呃......因为你正在创建一个额外的数组(而不是仅仅使用迭代器)。第一场比赛(其中,
是一个非缓冲流API)后的第一个方法停止。第二负载的所有的到一个数组(大概有几重的大小)比赛,然后采取的第一项。
作为一个方面说明;您可以创建无限序列; 。第一种方法,仍能正常工作,第二个将永远运行(或爆炸)
也有可能是:
VAR结果ErrorCodes.First(X => ReturnedErrorCodes.Contains(X));
(将不能使它更快,但也许更容易阅读)
I am running a test.
It looks like:
method 1)
List<int> = new List<int>{1,2,4, .....} //assume 1000k
var result ErrorCodes.Where(x => ReturnedErrorCodes.Contains(x)).First();
method 2)
List<int> = new List<int>{1,2,4, .....} //assume 1000k
var result = ErrorCodes.Where(x => ReturnedErrorCodes.Contains(x)).ToArray()[0];
Why is method 2 is so slow compared to method 1?
Erm... because you are creating an extra array (rather than just using the iterator). The first approach stops after the first match (Where
is a non-buffered streaming API). The second loads all the matches into an array (presumably with several re-sizes), then takes the first item.
As a side note; you can create infinite sequences; the first approach would still work, the second would run forever (or explode).
It could also be:
var result ErrorCodes.First(x => ReturnedErrorCodes.Contains(x));
(that won't make it any faster, but is perhaps easier to read)
这篇关于C#LINQ首先()比ToArray的(更快)[0]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!