马克有正确的答案,但魔鬼在细节中。
在我的机器上:
- 对于数组,.Length 比 .Count() 快大约 100 倍
- 对于列表,.Count 比 .Count() 快大约 10 倍 - 注意:我希望所有实现
IList<T> 的集合都有类似的性能
数组的启动速度较慢,因为 .Length 仅涉及单个操作,而 .Count 数组涉及一层间接。所以 .Count on arrays 开始慢 10 倍(在我的机器上),这可能是显式实现接口的原因之一。想象一下,如果您有一个具有两个公共属性 .Count 和 .Length 的对象。两者都做完全相同的事情,但 .Count 慢了 10 倍。
当然,这些都不会产生很大的不同,因为您必须每秒数百万次计算数组和列表才能感受到性能影响。
代码:
static void TimeAction(string description, int times, Action func) {
var watch = new Stopwatch();
watch.Start();
for (int i = 0; i < times; i++) {
func();
}
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}
static void Main(string[] args) {
var array = Enumerable.Range(0, 10000000).ToArray();
var list = Enumerable.Range(0, 10000000).ToArray().ToList();
// jit
TimeAction("Ignore and jit", 1 ,() =>
{
var junk = array.Length;
var junk2 = list.Count;
array.Count();
list.Count();
});
TimeAction("Array Length", 1000000, () => {
var tmp1 = array.Length;
});
TimeAction("Array Count()", 1000000, () =>
{
var tmp2 = array.Count();
});
TimeAction("Array Length through cast", 1000000, () =>
{
var tmp3 = (array as ICollection<int>).Count;
});
TimeAction("List Count", 1000000, () =>
{
var tmp1 = list.Count;
});
TimeAction("List Count()", 1000000, () =>
{
var tmp2 = list.Count();
});
Console.ReadKey();
}
结果:
Array Length Time Elapsed 3 ms
Array Count() 已用时间 264 毫秒
阵列长度通过施放时间经过 16 毫秒
列表计数时间经过 3 毫秒
列表计数()经过的时间 18 毫秒