Skip to content

Instantly share code, notes, and snippets.

@ihabunek ihabunek/slowref.md
Last active Nov 12, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Nov 12, 2018

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
You can’t perform that action at this time.