在 .NET 中,哪个循环运行得更快,“for"还是“foreach"? [英] In .NET, which loop runs faster, 'for' or 'foreach'?

查看:29
本文介绍了在 .NET 中,哪个循环运行得更快,“for"还是“foreach"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C#/VB.NET/.NET 中,for 还是 foreach 哪个循环运行得更快?

In C#/VB.NET/.NET, which loop runs faster, for or foreach?

自从我读到 for 循环比 foreach 循环工作得更快后,很久以前我认为它适用于所有集合、泛型集合、所有数组等.

Ever since I read that a for loop works faster than a foreach loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc.

我在谷歌上搜索并找到了几篇文章,但大多数都没有定论(阅读文章的评论)并且是开放式的.

I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.

最理想的做法是列出每个场景及其最佳解决方案.

What would be ideal is to have each scenario listed and the best solution for the same.

例如(只是它应该如何的一个例子):

For example (just an example of how it should be):

  1. 用于迭代 1000+ 的数组字符串 - for 优于 foreach
  2. 用于迭代 IList(非通用)字符串 - foreach 更好比 for
  1. for iterating an array of 1000+ strings - for is better than foreach
  2. for iterating over IList (non generic) strings - foreach is better than for

在网上找到了一些相同的参考:

A few references found on the web for the same:

  1. Emmanuel Schanzer 的原创大文章
  2. CodeProject FOREACH Vs.对于
  3. 博客 - foreach 还是不foreach,这是个问题
  4. ASP.NET 论坛 - NET 1.1 C# for vs foreach
  1. Original grand old article by Emmanuel Schanzer
  2. CodeProject FOREACH Vs. FOR
  3. Blog - To foreach or not to foreach, that is the question
  4. ASP.NET forum - NET 1.1 C# for vs foreach

除了可读性之外,我对事实和数据非常感兴趣.在某些应用程序中,最后一英里的性能优化很重要.

Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter.

推荐答案

首先,反驳Dmitry 的(现已删除)答案.对于数组,C# 编译器为 foreach 生成的代码与为等效的 for 循环生成的代码大致相同.这就解释了为什么这个基准测试的结果基本相同:

First, a counter-claim to Dmitry's (now deleted) answer. For arrays, the C# compiler emits largely the same code for foreach as it would for an equivalent for loop. That explains why for this benchmark, the results are basically the same:

using System;
using System.Diagnostics;
using System.Linq;

class Test
{
    const int Size = 1000000;
    const int Iterations = 10000;

    static void Main()
    {
        double[] data = new double[Size];
        Random rng = new Random();
        for (int i=0; i < data.Length; i++)
        {
            data[i] = rng.NextDouble();
        }

        double correctSum = data.Sum();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            for (int j=0; j < data.Length; j++)
            {
                sum += data[j];
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("For loop: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            foreach (double d in data)
            {
                sum += d;
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("Foreach loop: {0}", sw.ElapsedMilliseconds);
    }
}

结果:

For loop: 16638
Foreach loop: 16529

接下来,验证 Greg 关于集合类型很重要的观点 - 在上面将数组更改为 List,您会得到完全不同的结果.它不仅在一般情况下明显慢得多,而且 foreach 变得比通过索引访问慢得多.话虽如此,我仍然几乎总是更喜欢 foreach 而不是 for 循环,因为它使代码更简单 - 因为可读性几乎总是很重要,而微优化很少.

Next, validation that Greg's point about the collection type being important - change the array to a List<double> in the above, and you get radically different results. Not only is it significantly slower in general, but foreach becomes significantly slower than accessing by index. Having said that, I would still almost always prefer foreach to a for loop where it makes the code simpler - because readability is almost always important, whereas micro-optimisation rarely is.

这篇关于在 .NET 中,哪个循环运行得更快,“for"还是“foreach"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆