26

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.

7
  • 4
    should'nt really matter much, but I'll take a wild guess and say the bottom one is faster, but you'll probably never notice the difference. Commented Dec 18, 2012 at 9:04
  • 1
    stackoverflow.com/questions/771008/for-loop-vs-foreach-in-c Commented Dec 18, 2012 at 9:04
  • 1
    it all depends on your requirements and data with you. Commented Dec 18, 2012 at 9:05
  • 1
    microperformance is sometimes evil.... (Takes your attention away from where the actual bottleneck exists) Commented Dec 18, 2012 at 9:13
  • 1
    Benchmark: 3v4l.org/COc0o. Commented Sep 23, 2018 at 0:52

6 Answers 6

23

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).

Sign up to request clarification or add additional context in comments.

Comments

8

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

5 Comments

Would'nt for ($i=1000; $i--;) {} be even faster (all though in reverse) ?
@adeneo - Could be faster, possibly.... but you can run even faster by using --$i rather than $i--.... it still requires a few more iterations to actually see any difference in speed
Should be faster as there is no checking to see if the loop has gone past the limit, it just stops automagically when it reaches zero. In javascript on large iterations, I've actually noticed a bit difference, but never really bothered testing it in PHP.
@adeneo - of course, it all depends whether what you do within the loop is dependent on $i; and if so, does the order matter.... it's a nice trick, and I can see a couple of uses for it though
@adeneo in that case, better use while(--$i) {}, which is more readable and maybe faster.
1

comparing execution speed of some php functions

for loop took

for() loop using count() took 20.86401 ms

for() loop Not using count() took 7.09796 ms

using count() means: for ($i = 1; $i < count($myarr); ++ $i) {..

where as foreach() loop:

foreach() took 11.16920 ms

foreach() with KEY took 12.35318 ms

these both are done on same array and their respective execution time is shown both for and foreach are language constructs and their execution speed will be more so you cannot notice much more difference unless you are using them on an array with thousands of records.

Comments

0

Foreach is great for iterating through arrays that use keys and values.

For example, if I had an array called 'User':

$User = array(
    'name' => 'Bob',
    'email' => '[email protected]',
    'age' => 200
);

I could iterate through that very easily and still make use of the keys:

foreach ($User as $key => $value) {
    echo $key.' is '.$value.'<br />';
}

This would print out:

name is Bob
email is [email protected]
age is 200

With for loops, it's more difficult to retain the use of the keys.

When you're using object-oriented practice in PHP, you'll find that you'll be using foreach almost entirely, with for loops only for numerical or list-based things. foreach also prevents you from having to use count($array) to find the total number of elements in the array.

1 Comment

with for loop, it is not that difficult to iterate associative array. Just retreive the keys by array_keys() and rest same.
0

Foreach is great for iterating through arrays that use keys and values. With for loops, it's more difficult to retain the use of the keys. http://www.c-sharpcorner.com/interviews/answer/2147/ this may be helpful

Comments

0

In this particular case (with range() and not an array passed from another scope) - foreach() will be faster. for() would beat it in almost any other case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.