for($n=0; $n<$size; $n++) {
$x .= $arr[$n];
}
return $x;
}
function test_val($arr) {
$size = sizeof($arr);
for($n=0; $n<$size; $n++) {
$x .= $arr[$n];
}
return $x;
}
// fill array
for($n=0; $n<500000; $n++) {
$ar[] = "test".$n;
}
$Bs = array_sum(explode(' ', microtime()));
test_ref($ar);
echo "<br />The function using a reference took ".(array_sum(explode(' ', microtime()))-$Bs);
$Bs = array_sum(explode(' ', microtime()));
test_val($ar);
echo "<br />The funktion using a value took: ".(array_sum(explode(' ', microtime()))-$Bs);
The function using a reference took 10.035583019257
The funktion using a value took: 10.531390190125
Responding to Slava Kudinov. The only reason why your script takes longer when you pass by reference is that you do not at all modify the array that your passing to your functions. If you do that the diffrences in execution time will be a lot smaller. In fact passing by reference will be faster if just by a little bit.
In addition to the "array vs &array" example below, php 5.1.2. It seems passing an array by reference slower than by value, consider:
<?php
function test_ref(&$arr) {
$size = sizeof($arr);
for($n=0; $n<$size; $n++) {
$x = 1;
}
}
function test_val($arr) {
$size = sizeof($arr);
for($n=0; $n<$size; $n++) {
$x = 1;
}
}
for($n=0; $n<2000; $n++) {
$ar[] = "test".$n;
}
$time = microtime();
test_ref($ar);
echo "<br />The function using a reference took "
18/24 首页 上一页 16 17 18 19 20 21 下一页 尾页 |