For best practice cycle

As far as I know, the second and third expressions are executed every time in a for loop.

I always mistook the result provided, the second option was recommended, can anyone confirm this?

1) for($i=0;$i<=dosomething();$i++) [...]

2)

  $max = dosomething(); for($i=0;$i<=$max;$i++) [...] 
+6
source share
4 answers

You should not call a function inside the loop definition, because this function will execute every iteration. When you have only a small cycle, the effect is negligible, but if you have a cycle of hundreds or thousands of iterations, you will definitely notice.

But even if you only have a small cycle, this is just bad practice. So, in one word: not.

+5
source

If your dosomething () function returns different values, and this can be done with one shot, it is better to use the second method.

$ options = array (1,2,3,4,5); $ element_count = count ($ options);

Functions such as count () that return the same value in multiple calls can be stored in a single variable and used in a for loop.

If you are very strict about performance, use ++ $ i instead of $ i ++

+4
source

The second method will always reform better, especially if there is substantial work in doSomething (). If you execute only dozens of loops, and doSomething () just returns a local variable, then this will not make any noticeable difference.

+3
source

Yes I confirm that you can search for tests if you want.

Although I don't know if this is true if it is only a getter for an object

-2
source

Source: https://habr.com/ru/post/927063/


All Articles