Array cloning performance

We all know that

$a1 = array('foo');
$a2 = $a1;
$a2[0] = 'bar';
// now $a1[0] is foo, and $a2[0] is bar. The array is copied

However, what I remember reading, but cannot confirm Googling, is that the array is not internally copied until it is modified.

$a1 = array('foo');
$a2 = $a1; // <-- this should make a copy
// but $a1 and $a2 point to the same data internally
$a2[0] = 'bar';
// now $a1[0] is foo, and $a2[0] is bar. The array is really copied

I was wondering if this is true. If so, it will be fine. This would increase performance when iterating through a large array multiple times, but only reading from it anyway (after creating it once).

+3
source share
3 answers

It may be more than you wanted to know, but this article gives a good description of how variables work in PHP.

, , , .

+5

, :

<?php

ini_set('memory_limit', '64M');

function ttime($m) {
    global $s;
    echo $m.': '.(microtime(true) - $s).'<br/>';
    $s = microtime(true);
}

function aa($a) {
    return $a;
}

$s = microtime(true);
for ($i = 0; $i < 200000; $i++) {
    $array[] = $i;
}
ttime('Create');
$array2 = aa($array); // or $array2 = $array
ttime('Copy');
$array2[1238] = 'test';
ttime('Modify');

:

Create: 0.0956180095673
Copy: 7.15255737305E-6
Modify: 0.0480329990387
+1

I believe that you are faithful here. I will try to find documentation on this issue ... I can’t find anything about it, but I'm sure I read it somewhere. Hopefully someone here is lucky to find the documentation.

0
source

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


All Articles