Return by link

The PHP documentation says:

Do not use return-by-reference to improve performance. The engine automatically optimizes this on its own.

I want to return a reference to an array (which is a property of my class). How does PHP optimize this because the array is not an object?

If an array has 1 billion records, can I get two arrays with 1 billion records stored in memory if I do not pass it by reference?

+5
source share
1 answer

PHP uses copy when writing. This means that if you pass a huge array as a function parameter and only read it (e.g. foreach), you will not write to it, so it does not need to make a copy.

$count = count($huge_array); // read the reference at the bottom
for($i = 0; $i < $count $i++) {
    $value = 2*$huge_array[$i]/15;
    if($value > 3)
        $sub_array []= $value;
}

$subarray, ( ), () .

$_, , .

, .

, , PHP.

, , , , $large_array, $large_array .

, PHP .

, , , , , , .

PHP , , , .

function foo(&$data) {
    for ($i = 0; $i < strlen($data); $i++) {
        do_something($data{$i});
    }
}

$string = "... looooong string with lots of data .....";
foo(string);

strlen C . PHP . strlen , ().

, , , , ( ).

+5

All Articles