Which loop is faster, while or for?

后端 未结 16 2300
我寻月下人不归
我寻月下人不归 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:18

    In C#, the For loop is slightly faster.

    For loop average about 2.95 to 3.02 ms.

    The While loop averaged about 3.05 to 3.37 ms.

    Quick little console app to prove:

     class Program
        {
            static void Main(string[] args)
            {
                int max = 1000000000;
                Stopwatch stopWatch = new Stopwatch();
    
                if (args.Length == 1 && args[0].ToString() == "While")
                {
                    Console.WriteLine("While Loop: ");
                    stopWatch.Start();
                    WhileLoop(max);
                    stopWatch.Stop();
                    DisplayElapsedTime(stopWatch.Elapsed);
                }
                else
                {
                    Console.WriteLine("For Loop: ");
                    stopWatch.Start();
                    ForLoop(max);
                    stopWatch.Stop();
                    DisplayElapsedTime(stopWatch.Elapsed);
                }
            }
    
            private static void WhileLoop(int max)
            {
                int i = 0;
                while (i <= max)
                {
                    //Console.WriteLine(i);
                    i++;
                };
            }
    
            private static void ForLoop(int max)
            {
                for (int i = 0; i <= max; i++)
                {
                    //Console.WriteLine(i);
                }
            }
    
            private static void DisplayElapsedTime(TimeSpan ts)
            {
                // Format and display the TimeSpan value.
                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");
            }
        }
    

提交回复
热议问题