Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop best practice

Tags:

php

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

I always took for granted performance wise second option is recommended, can anyone confirm this?

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

2)

 $max = dosomething();
 for($i=0;$i<=$max;$i++) [...]
like image 812
wlf Avatar asked Oct 05 '12 21:10

wlf


1 Answers

You shouldn't call a function inside of a loop definition because that function will be executed every iteration. When you only have a small loop the effect is negligible, however if you have a loop of hundreds or thousands of iterations you'll definitely notice.

But even if you only have a small loop, it's just bad practice. So in a word: don't.

like image 119
VettelS Avatar answered Oct 01 '22 05:10

VettelS