Siddharth Thevaril Siddharth Thevaril - 3 months ago 8
PHP Question

Is it better to store array in a variable or directly pass an array to a function inside a loop?

Which of the 2 ways of passing array to a function inside a loop is recommended?

Are there any performance difference between them?

First method:

<?php

foreach ($variable as $val) {
$array = array(
'one' => $val->prop1,
'two' => $val->prop2,
);

some_function( $array );
}

?>


Second Method

<?php

foreach ($variable as $val) {
some_function( array(
'one' => $val->prop1,
'two' => $val->prop2,
));
}

?>

Answer

The first example you provided would have one more opcode than the second example, that is the ASSIGN opcode.

Though the performance difference between the two would be negligible, the second example would be a tiny bit faster than the first one, which you needn't need to worry about anyway.

And as you know,

Premature optimization is the root of all evil