Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it efficient to return an array in php?

I'm fairly new to PHP; most of my programming experience so far has been in C++. So, naturally, I get concerned about efficiency. In C++ you never ever ever return an object or an array at the end of a function, but if you need the data, you just return a pointer.

So my question is: is it bad for efficiency to be using arrays as return values, or does PHP just use a pointer in the background and just not show me for convenience?

like image 363
justinrixx Avatar asked Aug 21 '14 22:08

justinrixx


1 Answers

PHP returns a reference if it's optimal for the interpreter to do so. Normally parameters passed to functions are copied, though you pass a parameter by reference and therefore get a return value by reference like so:

function blah(&$foo) {
  $foo = array();//or whatever
  //note no return statement
}

//elsewhere
$x = "whatever";
blah($x);
//$x is now an array.

Because of &, $foo is treated as a reference, and so modifications to that variable are treated as modifications to the reference.

Or you can force the function to return a reference:

function &blah() {
  //some stuff
  return $foo;//goes back as a reference
}

This latter shouldn't, according to the docs, be done unless you have a non-optimization reason to do so.

That said, PHP isn't terribly efficient, and worrying about these things is generally premature - unless you're seeing an actual performance bottleneck in your code.

like image 166
Nathaniel Ford Avatar answered Oct 15 '22 01:10

Nathaniel Ford