Return value or change link?

I have seen it before, and as far as I know, it is largely subjective, but if an option is given, what would you do and why? If the data were large, would there be any advantage in speed / memory to one of them?

function processData(&$data_to_process) { // Pass by reference. // do something to the data } // ... somewhere else $this->processData($some_data); 

or

 function processData($data_to_process) { // Pass by value. // do something to the data return $data_to_process; } // ... somewhere else $some_data = $this->processData($some_data); 
+4
source share
2 answers

PHP copies when writing, so if the data does not change in the function, using the link only slows down.

In your case, you are changing the data, so copying will occur. Check the following:

 <?php define('N', 100000); $data = range(1, N); srand(1); function ref(&$data) { $data[rand(1, N)] = 1; } function ret($data) { $data[rand(1, N)] = 1; return $data; } echo memory_get_usage()."\n"; echo memory_get_peak_usage()."\n"; ref($data); // $data = ret($data); echo memory_get_usage()."\n"; echo memory_get_peak_usage()."\n"; ?> 

Run it once with ref() and once with ret() . My results:

ref ()

  • 8043280 (up / current)
  • 8044188 (before / peak)
  • 8043300 (after / current)
  • 8044216 (after / peak)

RET ()

  • 8043352 (up / current)
  • 8044260 (before / peak)
  • 8043328 (after / current)
  • 12968632 (after / peak)

So, as you can see, PHP uses more memory when changing data in a function and returning. Thus, the best case is passing by reference.

However, passing by reference can be dangerous if it is not obvious that it is happening. Often you can avoid this issue by encapsulating your data in classes that modify their own data.

Note that if you use objects, PHP5 always passes them by reference.

+5
source

In most cases, it is redundant to return the link that the caller already has, which happens in the second example. The only time I can figure out where this is useful is to call a chain of calls.

Typically, use a reference parameter when a function changes the state of this parameter and uses the return value to introduce something new to the caller.

0
source

All Articles