C# 为什么使用“foreach”的数组对象上的循环比lambda“foreach”快?
我在一个数组上工作,我必须在它上面循环。首先,我使用lambdaC# 为什么使用“foreach”的数组对象上的循环比lambda“foreach”快?,c#,foreach,C#,Foreach,我在一个数组上工作,我必须在它上面循环。首先,我使用lambdaForEach Array .ForEach<int>( array, ( int counter ) => { Console.WriteLine( counter ); } ); 数组 .ForEach(数组,(整数计数器)=>{ 控制台。写线(计数器); } ); 然后我使用simpleforeach。 我发现simpleforeach比lambdaforeach快得多,但是当我用泛型列表测试它
ForEach
Array
.ForEach<int>( array, ( int counter ) => {
Console.WriteLine( counter );
} );
数组
.ForEach(数组,(整数计数器)=>{
控制台。写线(计数器);
} );
然后我使用simpleforeach
。
我发现simpleforeach
比lambdaforeach
快得多,但是当我用泛型列表测试它时,foreach
比simpleforeach
快
为什么使用foreach
在数组对象上循环比lambdaforeach
快?
更新:
我在阵列上测试我发现在测试中lambda更快。复制粘贴MSDNs秒表代码并使用两个版本的迭代列表对其进行装饰。。。。(我还改变了测试的顺序,得到了相同的计时)。使用lambda的基于Linq的迭代速度更快
Lambda 00:00:00.49
foreach 00:00:00.58
还有密码
var list = Enumerable.Range(0, 100000000).ToArray();
var total = 0;
var stopWatch = new Stopwatch();
stopWatch.Start();
Array.ForEach(list, x => total += x);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
stopWatch = new Stopwatch();
stopWatch.Start();
foreach (var i in list)
{
total += i;
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
我编辑了基思的代码——在我的机器上,
foreach
的执行速度大约是Array的六倍。foreach
:
class Program
{
static void Main(string[] args)
{
Benchmark(50);
}
private static void Benchmark(int iterations)
{
int[] list = Enumerable.Range(0, 100000000).ToArray();
long sum = 0;
for (int i = 0; i < iterations; i++)
{
sum += ArrayForeach(list);
}
Console.WriteLine("ForEach " + sum / iterations);
sum = 0;
for (int i = 0; i < iterations; i++)
{
sum += Foreach(list);
}
Console.WriteLine("foreach " + sum / iterations);
}
private static long Foreach(int[] list)
{
long total = 0;
var stopWatch = Stopwatch.StartNew();
foreach (var i in list)
{
total += i;
}
stopWatch.Stop();
return stopWatch.ElapsedTicks;
}
private static long ArrayForeach(int[] list)
{
long total = 0;
var stopWatch = Stopwatch.StartNew();
Array.ForEach(list, x => total += x);
stopWatch.Stop();
return stopWatch.ElapsedTicks;
}
}
在调试中:
ForEach 941030
foreach 845443
- 它表明,
享受一些编译器优化,我想主要是在访问内存中的列表foreach
- 在调试中,运行lambda的开销看起来很高,而传递数字(按值)是造成差异的原因
我建议有更多时间的人看看Reflector…你称之为lambda foreach的东西实际上实现了惰性评估,因此有很多额外的代码。展示你的测试用例。我发现我的TestTest on array现在正好相反,两者都快,但lamda仍然是赢家,两者都快一点,但lambda还是比winshow快得多?介意在更新后的post?Nice测试中公布详细数据吗。我的结果:ForEach 1719909 ForEach 386685
ForEach 941030
foreach 845443