Which loop is faster, while or for?

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

    I was wondering the same thing so i googled and ended up here. I did a small test in python (extremely simple) just to see and this is what I got:

    For:

    def for_func(n = 0):
        for n in range(500):
            n = n + 1
    

    python -m timeit "import for_func; for_func.for_func()" > for_func.txt

    10000 loops, best of 3: 40.5 usec per loop

    While:

    def while_func(n = 0):
        while n < 500:
            n = n + 1
    

    python -m timeit "import while_func; while_func.while_func()" > while_func.txt

    10000 loops, best of 3: 45 usec per loop

提交回复
热议问题