views:

114

answers:

3

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 by Googling, is that the array is, internally, not 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, that would be good. It would increase performance when passing around a big array a lot, but only reading from it anyway (after creating it once).

A: 

I believe you are correct here. I will try to find documentation on this... I can't find anything about this, but I am sure that I read it somewhere. Hopefully someone here will have better luck finding the documentation.

KOGI
+1  A: 

I seem to have confirmed it:

<?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');

Gives:

Create: 0.0956180095673
Copy: 7.15255737305E-6
Modify: 0.0480329990387
Bart van Heukelom
+4  A: 

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

In general, you're correct that variables aren't copied until it's absolutely necessary.

JW
I believe it's called copy on write. It saves memory, and it means that the burden on the system is not when it is copied, but when the copy is modified. http://en.wikipedia.org/wiki/Copy-on-write
thomasrutter