Does it make sense to extract count($array) to a variable in a loop, performance-wise?
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:
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:
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: