Php Inspections (EA Extended)

A Static Code Analysis tool for PHP distributed as a PhpStorm / IdeaUltimate plugin.

View project on GitHub

Performance

This document covers changes to your code to improve php performance.

Static local variables

Note: the inspection is deactivated by default.

Note: the inspection brings less benefit for PHP 5.6+ due to non-editable array optimizations.

Static variables, defined in a function/method are not used widely and in nutshell representing static property visible only inside the function/method. As for any static variable, it is stored in memory until script is executed.

From performance point of view the technique is a micro-optimization with following benefits:

  • the variable is initialized only once;
  • the variable reused on repetitive calls without new memory allocation;
  • static variables can be used for replacing/hiding static class members;

Packed hashtable optimizations

Note: please reference this article for more technical details and real-life examples

PHP7 introduced significant improvements in performance and memory usage. One of improvements was an optimization of internals for associative arrays. To be more specific if an array has only integer keys organized in natural ascending order, then it will consume less memory and work a little bit faster with core array functions.

Php Inspections (EA Extended) checks array creation constructs and gives hints if found ways for enabling the optimizations.

Slow array function used in loop

Note: you might want to check benchmarks first - one, two

Synopsys: merging arrays in a loop causes high CPU usage and takes pretty much time for execution.

Let’s start with an example demonstrating the case:

    $options = [];
    foreach ($configurationSources as $source) {
        /* more logic here */
        
        $options = array_merge($options, $source->getOptions());
    }

In order to reduce execution time we can modify the code and perform the merge operation only once:

    $options = [];
    foreach ($configurationSources as $source) {
        /* more logic here */
        
        $options []= $source->getOptions(); // <- yes, we'll use a little bit more memory
    }
    /* PHP below 5.6 */
    $options = call_user_func_array('array_merge', $options);
    
    /* PHP 5.6+: more friendly to refactoring as less magic involved */
    $options = array_merge(...$options);