All posts
Published in PHP

PHP Loops — Which is faster?

Profile image of Atakan Demircioğlu
By Atakan Demircioğlu
Fullstack Developer

Foreach vs for in PHP, which is the fastest loop in PHP?

PHP Loops — Which is faster? image 1

These are my notes about PHP loops, which are faster, and so on.

I just compared it in one way and wrote the test results. It is important what do yo do inside the looping.

Note: echo is affecting testing performance. But it is ok for getting an idea that what happens when loops are working.

Using reference in foreach

Completed in 0.00046801567077637 Seconds
Completed in 0.00078511238098145 Seconds

Summary

  • It seems faster to not use references. When I get this result firstly I was surprised. The Zend Engine, PHP’s core, uses a copy-on-write optimization mechanism that does not create a copy of a variable until it is modified. Passing by reference usually breaks the copy-on-write pattern and requires a copy whether you modify the value or not.
  • Also using reference is dangerous in this case because after the foreach if you forgot to unset $v it can cause unwanted results.
  • So, in PHP 7+ pass-by-value is faster than pass-by-reference.
  • foreach($array as $item) will leave the variable $item untouched after the loop. If the variable is a reference, foreach($array as &$item)it will "point" to the last element of the array even after the loop.

Is for loop faster than foreach?

  • With your usage or need, it can be changed actually. For this example we can say for is faster than foreach.
  • In most cases, foreach is more readable than for.

What is the fastest loop?

  • In Google, it seems do-while is the fastest loop in PHP. For this example (modifying an array in the same way), while for and do-while have near performance.
  • Also, a good thing to know, the do while loop only has one jump statement (JMPNZ), whereas the while loop needs two (JMPZ, JMP). The for loop needs three jump statements (JMPZNZ, JMP, JMP) and has generally more complex logic. That is why do-while is faster. (opcodes)

References

 

How To Secure PHP Sessions?
My notes about how to secure PHP Sessions, what is session hijacking, and so on.atakde.medium.com

JIT Compiler in PHP
Here are my notes about the JIT compiler in PHP.atakde.medium.com

PHP Magic Methods Explained
PHP Magic methods explained. What are the PHP Magic methods?atakde.medium.com