Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance of array cloning

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).

like image 952
Bart van Heukelom Avatar asked Dec 30 '25 07:12

Bart van Heukelom


1 Answers

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.

like image 102
JW. Avatar answered Dec 31 '25 22:12

JW.