I've just found something very strange in PHP.
If I pass in a variable to a function by reference, and then call a function on it, it's incredibly slow.
If you loop over the inner function call and the variable is large it can be many orders of magnitude slower than if the variable is passed by value.
Example:
<?php
function TestCount(&$aArray)
{
$aArray = range(0, 100000);
$fStartTime = microtime(true);
for ($iIter = 0; $iIter < 1000; $iIter++)
{
$iCount = count($aArray);
}
$fTaken = microtime(true) - $fStartTime;
print "took $fTaken seconds\n";
}
$aArray = array();
TestCount($aArray);
?>
This consistently takes about 20 seconds to run on my machine (on PHP 5.3).
But if I change the function to pass by value (ie function TestCount($aArray)
instead of function TestCount(&$aArray)
), then it runs in about 2ms - literally 10,000 times faster!
The same is true for other built-in functions such as strlen
, and for user-defined functions.
What's going on?