it means that this:
$maxvalue = 100/10; for($i=0; $i<$maxvalue; $i++){ // Some code }
is much faster than this:
for($i=0; $i<100/10; $i++){ // Some code }
because the value is calculated once instead of ten times.
$maxvalue = 100/10; for($i=0; $i<$maxvalue; $i++){ // Some code }
is much faster than this:
for($i=0; $i<100/10; $i++){ // Some code }
because the value is calculated once instead of ten times.
mbp:~/test doug$ time php -r 'for ($i=1; $i<100000000/10; $i++) {$x++;};'
real 0m5.930s
user 0m5.867s
sys 0m0.026s
mbp:~/test doug$ time php -r '$maxval=100000000/10; for ($i=1; $i<$maxval; $i++) {$x++;};'
real 0m6.999s
user 0m6.907s
sys 0m0.029s
mbp:~/test doug$ time perl -e 'for ($i=1; $i<100000000/10; $i++) {$x++;}'
real 0m2.520s
user 0m2.496s
sys 0m0.010s
mbp:~/test doug$ time perl -e '$maxval=100000000/10; for ($i=1; $i<$maxval; $i++) {$x++;}'
real 0m2.537s
user 0m2.499s
sys 0m0.014s
The results are a little different with Python (maxval1.py computes inline; maxval2 divides in advance and uses variable inline) mbp:~/test doug$ time python maxval1.py
real 0m2.134s
user 0m1.761s
sys 0m0.276s
mbp:~/test doug$ time python maxval2.py
real 0m1.890s
user 0m1.588s
sys 0m0.278s
Java shows even more of a difference (again, maxval2 sets variable in advance): mbp:~/test doug$ time java maxval1
real 0m0.174s
user 0m0.116s
sys 0m0.040s
mbp:~/test doug$ time java maxval2
real 0m0.531s
user 0m0.125s
sys 0m0.041s
for i in range(1, 100000000/10):
pass
And here is maxval2.py: maxval=100000000/10
for i in range(1, maxval):
pass
public class maxval1 {
static int $i, $x;
public static void main(String args[]) throws Exception {
for ($x=$i=1; $i<100000000/10; $i++) {$x++;}
System.out.println($x);
}
}
And maxval2.java: public class maxval2 {
static int $a, $i, $x;
public static void main(String args[]) throws Exception {
$a=100000000/10;
for ($x=$i=1; $i<$a; $i++) {$x++;}
System.out.println($x);
}
}
> Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.