Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP for loop vs. foreach with range [closed]

Tags:

Which of these would be better for performance and readability?

foreach(range(0,10000) as $i) {} // 3.847 ms

for($i = 0; $i < 10000; ++$i) {} // 0.663 ms

Edit: Did a benchmark and the last one was almost 6 times faster.

like image 852
Emil Aspman Avatar asked Dec 18 '12 09:12

Emil Aspman


2 Answers

Traditional for loop is faster than foreach + range. The first one only uses integer comparison and increasing while the last one has to create an (possibly big) array and then extract each element by moving the internal array cursor and checking whether the end is reached.

If you execute this you can see that plain for is twice faster than foreach + range:

$t0 = microtime(true);
for ($i = 0; $i < 100000; $i++) {
}
echo 'for loop: ' . (microtime(true) - $t0) . ' s', PHP_EOL;

$t0 = microtime(true);
foreach (range(0, 100000) as $i) {
}
echo 'foreach + range loop: ' . (microtime(true) - $t0) . ' s', PHP_EOL;

It is better to use traditional for as a habit in the case you need to iterate a given number of times but at the end of the day you won't see big performance improvements in most scenarios (take into account that the example above iterates 100k times, if you reduce the number of iterations, the difference is smaller).

like image 117
Carlos Avatar answered Oct 31 '22 21:10

Carlos


If it's that critical,

for($i = 0; $i < 1000; ++$i) {}

is faster than

for($i = 0; $i < 1000; $i++) {}

but you'll not really notice much difference over just 1000 iterations

Is it really so essential to micro-optimize.... and if so, why can't you simply set up some test runs to compare the different options yourself

like image 29
Mark Baker Avatar answered Oct 31 '22 22:10

Mark Baker