Why does the second for loop always execute faster than the first one?

前端 未结 8 1226
日久生厌
日久生厌 2021-01-05 11:14

I was trying to figure out if a for loop was faster than a foreach loop and was using the System.Diagnostics classes to time the task. While running the test I noticed that

8条回答
  •  隐瞒了意图╮
    2021-01-05 12:06

    I was just performing tests to get some real numbers, but in the meantime Gaz beat me to the answer - the call to Console.Writeline is jitted at the first call, so you pay that cost in the first loop.

    Just for information though - using a stopwatch rather than the datetime and measuring number of ticks:

    Without a call to Console.Writeline before the first loop the times were

    for: 16802
    foreach: 2282
    

    with a call to Console.Writeline they were

    for: 2729
    foreach: 2268
    

    Though these results were not consistently repeatable because of the limited number of runs, but the magnitude of difference was always roughly the same.


    The edited code for reference:

            int[] x = new int[] { 3, 6, 9, 12 };
            int[] y = new int[] { 3, 6, 9, 12 };
    
            Console.WriteLine("Hello World");
    
            Stopwatch sw = new Stopwatch();
    
            sw.Start();
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine(x[i]);
            }
            sw.Stop();
            long elapsedTime = sw.ElapsedTicks;
    
            sw.Reset();
            sw.Start();
            foreach (var item in y)
            {
                Console.WriteLine(item);
            }
            sw.Stop();
            long elapsedTime2 = sw.ElapsedTicks;
    
            Console.WriteLine("\nSummary");
            Console.WriteLine("--------------------------\n");
            Console.WriteLine("for:\t{0}\nforeach:\t{1}", elapsedTime, elapsedTime2);
    
            Console.ReadKey();
    

提交回复
热议问题