Is PHP capable of caching a call counter inside a loop?

I know that a more efficient way to have a loop over an array is to foreach or store the count in a variable to avoid calling it several times. But I'm curious if PHP has any β€œcaching” things like:

for ($i=0; $i<count($myarray); $i++) { /* ... */ } 

Does it have something like this, and I skip it, or does it have nothing, and you should encode:

 $count=count($myarray); for ($i=0; $i<$count; $i++) { /* ... */ } 
+4
source share
3 answers

PHP does exactly what you tell it. The length of the array can change inside the loop, so it may be special that you call count at each iteration. PHP is not trying to deduce what you have in mind here, and should not. Therefore, the standard way to do this is:

 for ($i = 0, $length = count($myarray); $i < $length; $i++) 
+14
source

PHP will do the counting every time the loop repeats. However, PHP maintains an internal track of the size of the array, so counting is a relatively cheap operation. This is not as if PHP literally counted every element in the array. But he is still not free.

Using a very simple 10 mm element array that performs a simple variable increment, I get 2.5 seconds for the loop version in the loop and 0.9 seconds for the count-before-loop loop. Quite a big difference, but not "massive".

edit: code:

 $x = range(1, 10000000); $z = 0; $start = microtime(true); for ($i = 0; $i < count($x); $i++) { $z++; } $end = microtime(true); // $end - $start = 2.5047581195831 

Switch to do

 $count = count($x); for ($i = 0; $i < $count; $i++) { 

and otherwise everything else is the same, time is 0.96466398239136

+3
source

PHP is an imperative language, and this means that it does not have to optimize anything that can have any effect. Given that this is also an interpreted language, this cannot be done safely, even if someone really wanted to.

Also, if you just want to iterate over an array, you really want to use foreach . In this case, not only the account will be copied, but also the entire array (and you can change the original one as you wish). Or you can change it in place using foreach ($arr as &$el) { $el = ... }; unset($el); foreach ($arr as &$el) { $el = ... }; unset($el); . I want to say that PHP (like any other language) often provides better solutions for your original problem (if any).

0
source

Source: https://habr.com/ru/post/1401522/


All Articles