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);
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.
source share