问题描述
可能重复:结果
Is它更好地在LINQ查询调用了ToList()或ToArray的()?
我有code是这样的:
I have code like this:
void Foobar(string[] arr, Dictionary<string, string[]>)
{
var t = arr.Intersect(dic.Keys).ToList(); // .or ToArray() ?
foreach(var item in t)
{
..
}
var j = t.Count; // also I need this
}
该方法preferred?
which method is preferred?
我可以去没有任何,但我需要知道的大小,我不想叫 Enumerable.Count&LT; T&GT;()
- 似乎看做多行动则阵列&LT; T&GT; .Size
或列表&LT; T&GT; .Count之间
。我说得对不对?
I could go without any but I need to know the size and I don't want to call Enumerable.Count<T>()
- it seems do do more actions then Array<T>.Size
or List<T>.Count
. Am I right?
推荐答案
其实,在当前的MS执行伯爵(IEnumerable的)还有找一个快捷方式,如果IEnumerable的是一个ICollection的,并呼吁指望它。这样的表现应该是计算元素相媲美。
Actually, in the current MS implementation of Count(IEnumerable) there's a shortcut looking if the IEnumerable is an ICollection and calls Count on it. So the performance should be comparable for counting elements.
了ToList和ToArray的都有点相同。如果IEnumerable的是一个ICollection的,则CopyTo方法被调用来代替,这是一个有点快。
ToList and ToArray are a bit the same. If the IEnumerable is a ICollection, then the CopyTo method is called instead, which is a bit faster.
所以,选择什么使你的code最可读的,和基准您的使用情况有一个明确的答案。
So, choose what makes your code the most readable, and benchmark for YOUR use case to have a definite answer.
更新:
我做了一个天真的基准。
Update:I did a naive benchmark.
与Array开始: VAR项目= Enumerable.Range(1,1000).ToArray();
- 调用了ToList():为25ms / 10000
- 调用ToArray的():23毫秒/ 10000
与开始一个IEnumerable VAR项目= Enumerable.Range(1,1000);
Starting with an IEnumerable: var items = Enumerable.Range(1,1000);
- 调用了ToList():168ms / 10000
- 调用ToArray的():171 MS / 10000
所以基本上你得到相当的性能。
So basically you get comparable performance.
这篇关于我需要遍历和计数。什么是最快或preferred:ToArray的()或了ToList()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!