Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach changes in PHP7

Tags:

foreach

php

php-7

foreach in PHP7 by default, when iterating by value, operates on a copy of the array according to: http://php.net/manual/en/migration70.incompatible.php

Does it lazily create a copy only if there are changes made to the array or a value or will it always make a copy and in essence make looping over references a performance optimization?

Also, do arrays of objects still loop over/give you references of the objects? Or will they actually also create copies for the foreach and return the objects by value?

like image 567
inquam Avatar asked Dec 04 '15 20:12

inquam


People also ask

Does foreach mutate array?

forEach() does not mutate the array on which it is called. (However, callback may do so).

Is foreach slower than for PHP?

The 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed. For improved performance, the concept of references needs to be used.

Is foreach faster than for PHP?

I also don't see manipulating arrays with more than 1000 keys happening on a regular basis, but I do see a array being traversed multiple times in the logic of a application! Also as for operations, largely only string manipulation and echo'ing. In short: foreach is faster than foreach with reference.


1 Answers

In PHP 7, if you iterate an array by value, the copy will be done lazily, only when and if the array is actually modified.

If you iterate an array by reference instead, a separation will be performed at the start of the loop. If the array is currently used in more than one place, this separation will lead to a copy.

Furthermore iterating by reference means that a) the array has to be wrapped into a reference and b) each element has to be wrapped in a reference as well. Creating a reference wrapper is an expensive operation, because it requires allocation.

Additionally iteration by reference requires us to use a modification-safe iteration mechanism. This works by registering the iterator with the array and checking for potentially affected iterators in various array modification operations.

So no, iterating by reference is certainly not an optimization, it's a de-optimization. Using references usually is.

like image 192
NikiC Avatar answered Sep 22 '22 10:09

NikiC