Skip to content

Instantly share code, notes, and snippets.

@ihabunek
Last active November 12, 2018 22:54
Show Gist options
  • Save ihabunek/6375653 to your computer and use it in GitHub Desktop.
Save ihabunek/6375653 to your computer and use it in GitHub Desktop.
PHP: Passing a large referenced array into a function is slow

PHP: Passing a large referenced array into a function is slow

This is interesting.

<?php 

define ('ITEMS', 1000);
define ('REPEAT', 10000);

// A function which does nothing
function foo($array) {}

// A largish array
$array = array_fill(0, ITEMS, 'whatever');

// An unused reference to the array
$reference = &$array;

// Start timer
$start = microtime(true);

// Call function which does nothing, pass array as param
for ($i=0; $i < REPEAT; $i++) {
    foo($array);
}

// End timer
$duration = microtime(true) - $start;
$duration = number_format($duration, 4);
echo "Duration: {$duration}s\n";

Running this code (on a reasonably fast server, PHP 5.5) yields:

Duration: 0.5552s

However, if you comment out the line which assigns the (unused) refence:

// $reference = &$array;

Things get much faster:

Duration: 0.0022s
@matejb
Copy link

matejb commented Aug 29, 2013

But if you add reference to function parametar:

function foo(&$array) {}
Duration: 0.0045s

Is it possible new variable in function parameter caries reference duplication and eat's memory!?

@imotion-software
Copy link

Hi!

this is fully replicable in all PHP5 versions and there's no official PHP bug open.
We're facing the same strange behavior.

Did you get the reason for this behavior or a reasonable way to fix it?

We got the same also with standard php functions (like "current" and "key") and it's not possibile to simply add a "&" in the prototype.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment