Which loop is faster, while or for?

后端 未结 16 2316
我寻月下人不归
我寻月下人不归 2020-11-27 07:07

You can get the same output with for and while loops:

While:

$i = 0;
while ($i <= 10){
  print $i.\"\\n\";
  $i++;
};
         


        
16条回答
  •  旧巷少年郎
    2020-11-27 07:19

    I also tried to benchmark the different kinds of loop in C#. I used the same code as Shane, but I also tried with a do-while and found it to be the fastest. This is the code:

    using System;
    using System.Diagnostics;
    
    
    public class Program
    {
        public static void Main()
        {
            int max = 9999999;
            Stopwatch stopWatch = new Stopwatch();
    
            Console.WriteLine("Do While Loop: ");
            stopWatch.Start();
            DoWhileLoop(max);
            stopWatch.Stop();
            DisplayElapsedTime(stopWatch.Elapsed);
            Console.WriteLine("");
            Console.WriteLine("");
    
            Console.WriteLine("While Loop: ");
            stopWatch.Start();
            WhileLoop(max);
            stopWatch.Stop();
            DisplayElapsedTime(stopWatch.Elapsed);
            Console.WriteLine("");
            Console.WriteLine("");
    
            Console.WriteLine("For Loop: ");
            stopWatch.Start();
            ForLoop(max);
            stopWatch.Stop();
            DisplayElapsedTime(stopWatch.Elapsed);
        }
    
        private static void DoWhileLoop(int max)
        {
            int i = 0;
            do
            {
                //Performe Some Operation. By removing Speed increases
                var j = 10 + 10;
                j += 25;
                i++;
            } while (i <= max);
        }
    
        private static void WhileLoop(int max)
        {
            int i = 0;
            while (i <= max)
            {
                //Performe Some Operation. By removing Speed increases
                var j = 10 + 10;
                j += 25;
                i++;
            };
        }
    
        private static void ForLoop(int max)
        {
            for (int i = 0; i <= max; i++)
            {
                //Performe Some Operation. By removing Speed increases
                var j = 10 + 10;
                j += 25;
            }
        }
    
        private static void DisplayElapsedTime(TimeSpan ts)
        {
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");
        }
    }
    

    and these are the results of a live demo on DotNetFiddle:

    Do While Loop:
    00:00:00.06

    While Loop:
    00:00:00.13

    For Loop:
    00:00:00.27

提交回复
热议问题