In .NET, which loop runs faster, 'for' or 'foreach'?

前端 未结 30 1372
抹茶落季
抹茶落季 2020-11-22 04:25

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

Ever since I read that a for loop works faster than a foreach

30条回答
  •  忘了有多久
    2020-11-22 04:46

    This should save you:

    public IEnumerator For(int start, int end, int step) {
        int n = start;
        while (n <= end) {
            yield n;
            n += step;
        }
    }
    

    Use:

    foreach (int n in For(1, 200, 4)) {
        Console.WriteLine(n);
    }
    

    For greater win, you may take three delegates as parameters.

提交回复
热议问题