Does it make sense to extract count($array) to a variable in a loop, performance-wise?

Vastly
1 min readFeb 16, 2020

If you use famous PHPStorm’s “PHP Inspections [EA Extended]” plugin, you are probably aware of the following warning, saying that you need to consider removing any callables from loop conditionals:

PHP Inspections warning about callables in loop conditionals

But is there any performance gain in the most common, trivial cases like count() call against an array? Maybe PHP engine is smart enough to do it internally? Let’s measure it! Let’s take a look at the following benchmark:

script for phpbench

Full source code of the benchmark is available on Github.

Results

Long story short, count() call in a loop makes the execution ≈ 2.5x slower, no matter what is the size of the array:

2.5x slower loop if you don’t create a variable to store size of the collection

--

--