7

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?

7
  • You can pass by reference in PHP too. Commented Aug 21, 2014 at 22:46
  • 2
    yes its efficient, PHP uses references in the background, good question by the way! +1 Commented Aug 21, 2014 at 22:46
  • 2
    As for development, it's more efficient to look at profiler graphs (and preferrably database queries then) instead of worrying about performance minutae over readability beforehand. Commented Aug 21, 2014 at 22:47
  • 2
    @user2864740 Actually PHP does copy-on-write and the result is that references can even be slower than straight copies. See for example php.net/manual/en/internals2.variables.intro.php and schlueters.de/blog/archives/125-Do-not-use-PHP-references.html Commented Aug 21, 2014 at 23:03
  • 1
    @jeroen Thanks for the link. I didn't realize it utilized CoW. Commented Aug 21, 2014 at 23:11

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.