假设您需要一个需要频繁迭代的整数列表/数组,我的意思是非常频繁。原因可能有所不同,但可以说它位于大容量处理的最内层循环的核心。
一般来说,人们会选择使用列表(List),因为它们的大小具有灵活性。最重要的是,msdn 文档声称列表在内部使用数组,并且执行速度应该一样快(使用 Reflector 快速查看即可证实这一点)。无论如何,这会涉及一些开销。
有没有人真正测量过这个?在列表中迭代 6M 次会花费与数组相同的时间吗?
非常容易测量...
在少量紧循环处理代码中我知道长度是固定的我使用数组进行额外的微小优化;数组可以是边际地 faster if您使用索引器 / 来表示表单 - 但 IIRC 认为这取决于数组中数据的类型。但除非你need微观优化,保持简单并使用List<T>
etc.
当然,这仅适用于您正在读取所有数据的情况;对于基于键的查找,字典会更快。
这是我使用“int”的结果(第二个数字是校验和,以验证它们都做了相同的工作):
(已编辑以修复错误)
List/for: 1971ms (589725196)
Array/for: 1864ms (589725196)
List/foreach: 3054ms (589725196)
Array/foreach: 1860ms (589725196)
基于测试台:
using System;
using System.Collections.Generic;
using System.Diagnostics;
static class Program
{
static void Main()
{
List<int> list = new List<int>(6000000);
Random rand = new Random(12345);
for (int i = 0; i < 6000000; i++)
{
list.Add(rand.Next(5000));
}
int[] arr = list.ToArray();
int chk = 0;
Stopwatch watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
int len = list.Count;
for (int i = 0; i < len; i++)
{
chk += list[i];
}
}
watch.Stop();
Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);
chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
for (int i = 0; i < arr.Length; i++)
{
chk += arr[i];
}
}
watch.Stop();
Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);
chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
foreach (int i in list)
{
chk += i;
}
}
watch.Stop();
Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);
chk = 0;
watch = Stopwatch.StartNew();
for (int rpt = 0; rpt < 100; rpt++)
{
foreach (int i in arr)
{
chk += i;
}
}
watch.Stop();
Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);
Console.ReadLine();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)