Answers:
using System.Linq;
...
double total = myList.Sum(item => item.Amount);
这是您可以运行以进行此类测试的示例代码:
var f = 10000000;
var p = new int[f];
for(int i = 0; i < f; ++i)
{
p[i] = i % 2;
}
var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);
int x = 0;
time = DateTime.Now;
foreach(var item in p){
x += item;
}
Console.WriteLine(DateTime.Now - time);
x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
x += p[i];
}
Console.WriteLine(DateTime.Now - time);
复杂对象的相同示例是:
void Main()
{
var f = 10000000;
var p = new Test[f];
for(int i = 0; i < f; ++i)
{
p[i] = new Test();
p[i].Property = i % 2;
}
var time = DateTime.Now;
p.Sum(k => k.Property);
Console.WriteLine(DateTime.Now - time);
int x = 0;
time = DateTime.Now;
foreach(var item in p){
x += item.Property;
}
Console.WriteLine(DateTime.Now - time);
x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
x += p[i].Property;
}
Console.WriteLine(DateTime.Now - time);
}
class Test
{
public int Property { get; set; }
}
关闭编译器优化的结果是:
00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)
对于第二项测试是:
00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()
看起来LINQ通常比foreach(...)慢,但是对我来说奇怪的是foreach(...)似乎比for循环快。
Stopwatch
在System.Diagnostics
,因为它是一个高性能的时间记录。(顺便说一句,我没打败您)
DateTime.Now
用于测量。它总是返回本地时间,因此性能很差。DateTime.UtcNow
是比较快的; 但是,它仍然没有使用Stopwatch
该类的高分辨率。