In PHP, how do we return a large array?

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 inefficient to return such a large array as it "returns a value"? (say, if it is not 1,000, but 1,000,000). To improve it, will we change the first line to:

 function &bar() { 

that is, simply adding & in front of the function name is the correct and preferred way if a large array is returned?

+6
source share
5 answers

There are many misunderstandings about how PHP handles variable storage. Since PHP is a "copy on write", there is no need to create a "link" (actually an alias of a character table) to save space or time. In fact, it can hurt you. You should only create a link to PHP if you want to use it as an alias for something. I ran both of your snippets, and it looks like the second one actually uses more memory (albeit not much).

By the way, an array of 1000 integers is tiny.

+7
source

They consume exactly the same amount of memory due to COW

PS: to pass the "truth" by reference, you also need to add it to the assignment:

 $ha =& bar(); 
+5
source

If you select memory_get_peak_usage() in the function and externally, you will see that returning the array does not increase memory.

PHP copies when writing. In this case, there is nothing to copy, even if you write, because the original variable is beyond the scope. No, there is no reason for this.

And in fact, in PHP there is no reason to use links at all if you don't need the functionality they provide: changing the original variable.

+3
source

The official manual page says: Returning by reference is useful if you want to use a function to find which variable the binding should be bound to. Do not use the backlink to increase performance. The engine automatically optimizes this on its own. Only return links when you have a good technical reason for this.

http://it2.php.net/manual/en/language.references.return.php

So in your case do not use it.

+1
source

How about this?

 function bar($result) { $result = array(); for ($i = 0; $i < 1000; $i++) { $result[] = $i * 10; } } bar(&$ha); print_r($ha); 
0
source

Source: https://habr.com/ru/post/914681/


All Articles