Is passing by reference faster in foreach
when you want to change the value in the array?
For instance,
$a = array (
0 => array(
'title' => 'x',
'content' => 'x',
'time' => 'x'
),
1 => array(
'title' => 'x',
'content' => 'x',
'time' => 'x'
),
2 => array(
'title' => 'x',
'content' => 'x',
'time' => 'x'
)
);
function stripData(array $a)
{
return array(
'title' => $a['title'],
'content' => $a['content']
);
}
without reference
$b = array();
$begin = microtime(true);
foreach ($a as $v) {
$b[] = stripData($v);
}
$end = microtime(true);
echo $end - $begin . "
"; // 1.38282775879E-5
with reference
$begin = microtime(true);
foreach ($a as &$v) {
$v = stripData($v);
}
$end = microtime(true);
echo $end - $begin . "
"; // 4.05311584473E-6
I tested it on http://phpfiddle.org/ but the #1 seems to be faster while #2 (reference) is a lot slower.
Any ideas?
What would you do in the case like this? Would you do the #1 or #2? Using the reference is less code obviously!