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

前端 未结 30 1993
抹茶落季
抹茶落季 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:33

    Any time there's arguments over performance, you just need to write a small test so that you can use quantitative results to support your case.

    Use the StopWatch class and repeat something a few million times, for accuracy. (This might be hard without a for loop):

    using System.Diagnostics;
    //...
    Stopwatch sw = new Stopwatch()
    sw.Start()
    for(int i = 0; i < 1000000;i ++)
    {
        //do whatever it is you need to time
    }
    sw.Stop();
    //print out sw.ElapsedMilliseconds
    

    Fingers crossed the results of this show that the difference is negligible, and you might as well just do whatever results in the most maintainable code

提交回复
热议问题