Reputation: 3810
Say if this is the code:
function bar() {
$result = array();
for ($i = 0; $i < 1000; $i++) {
$result[] = $i * 10;
}
return $result;
}
$ha = bar();
print_r($ha);
Is it not efficient to return a large array like that since it is "return by value"? (say if it is not 1000 but 1000000). So to improve it, would we change the first line to:
function &bar() {
that is, just by adding an &
in front of the function name -- is this a correct and preferred way if a large array is returned?
Upvotes: 6
Views: 1317
Reputation: 255025
They consume absolutely the same amount of memory, because of COW
PS: to get "true" passing by reference you also need to add it in the assignment:
$ha =& bar();
Upvotes: 5
Reputation: 10349
Official manual page says: Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so
https://www.php.net/manual/en/language.references.return.php
So, in your case, don't use it.
Upvotes: 1
Reputation: 48304
If you throw in a memory_get_peak_usage()
in the function and outside, you'll see that returning the array does not increase the memory.
PHP copies on write. In this case, there is nothing to copy even if you do write because the original variable is out of scope. So no, there is no reason to do this.
And in fact, in PHP, there's generally no reason to use references unless you need the functionality that they provide: altering the original variable.
Upvotes: 3
Reputation: 25
What about this?
function bar($result) {
$result = array();
for ($i = 0; $i < 1000; $i++) {
$result[] = $i * 10;
}
}
bar(&$ha);
print_r($ha);
Upvotes: 0
Reputation: 191789
There is a lot of misunderstanding about how PHP handles variable storage. Since PHP is "copy on write," there is no need to create a "reference" (actually a symbol table alias) in an effort to save space or time. In fact, doing so can hurt you. You should only create a reference in PHP if you want to use it as an alias to something. I ran both of your snippets, and it looks like the second actually uses more memory (though not by much).
By the way, an array of 1000 integers is tiny.
Upvotes: 8