Home > Net >  PHP: Question of static arrays inside functions
PHP: Question of static arrays inside functions

Time:05-29

This is unrelated to OOP. All I want to know is how practical is using static arrays in functions and does it impact performance in the same way as if they were re-initialized every time on function call or actually less?

Example:

function color($key)
{
    static $arr = ["Blue", "Green", "Red", "Yellow"];
    return $arr[$key];
}

CodePudding user response:

Ok, since I'm still using PHP 7.0 I had to give up hrtime() and resort to good old microtime(). Here's my version of the test, which includes direct array access outside a function:

function color1()
{
    $arr = ["Blue", "Green", "Red", "Yellow"];
    return $arr;
}

function color2()
{
    static $arr = ["Blue", "Green", "Red", "Yellow"];
    return $arr;
}

$arr = ["Blue", "Green", "Red", "Yellow"];
$start = microtime(true);
for ($i = 0; $i < 10000000; $i  )
{
    $arr[0];
}
$end = microtime(true);
echo 'Time 1: ' . ($end - $start);

$start = microtime(true);
for ($i = 0; $i < 10000000; $i  )
{
    color1()[0];
}
$end = microtime(true);
echo '<br>Time 2: ' . ($end - $start);

$start = microtime(true);
for($i = 0;$i < 10000000; $i  )
{
    color2()[0];
}
$end = microtime(true);
echo '<br>Time 3: ' . ($end - $start);

The results are thus:

Direct array access: 1.7380030155182

Function array (non-static): 9.6041390895844

Function array (static): 8.5652348995209

As you can see, the static version prevails over the non-static, but not by a large margin. Overall, it's the same story. And, of course, reading the array contents directly is considerably faster. However, I discovered it's not really the array per se which is the bottleneck here, but the function call itself. Testing function test() { return true; } measured up to 6.8210098743439!!! So take that and 1.7380030155182 of the first result and you pretty much get the same thing. Of course, it happens only once when you call the function to assign the returned array value to external variable.

CodePudding user response:

When you ask for performance, you can just try :

function color1($key)
{
    $arr = ["Blue", "Green", "Red", "Yellow];
    return $arr[$key];
}

function color2($key)
{
    static $arr = ["Blue", "Green", "Red", "Yellow];
    return $arr[$key];
}
$time1=hrtime(true);
for ($i=0;$i<1000;$i  ) {
 color1(0);
}
$time2=hrtime(true);
echo ‘Execution Time without static in ns :’ . ($time2-$time1);
$time1=hrtime(true);
for ($i=0;$i<1000;$i  ) {
 color2(0);
}
$time2=hrtime(true);
echo ‘Execution Time with static in ns :’ . ($time2-$time1);

It will give you very precise execution Time (in ns).

  • Related