Copy on write

posted on: 2011-01-02 17:46:10




When using a language like php it's easy to forget about what is happening in the background when we perform even very simple operations such as a copy of an array. When we make a copy of an array, PHP initially creates a reference to the original array we are taking a copy of. Only when the original array or any of the subsequent copys are edited will a deep copy take place. This can be observed in the short test below.

Lets start by populating an array. We can observe the memory used by using the memory_get_usage function.

 
print('starting memory: '.memory_get_usage().'<br />');

$array_of_i = array();

for($i=0; $i<10000; $i++) { 
	$array_of_i[$i] = $i; 
}

print('initial array created: '.memory_get_usage().'<br />');


Next we make a copy of our array.

$copy_of_array = $array_of_i;

print('initial array copied: '.memory_get_usage().'<br />');


Now when we decide to edit our copied array.

$copy_of_array[1] = 0;

print('writing to copied array: '.memory_get_usage().'<br />');


The execution output:

starting memory: 317740
initial array created: 1423688
initial array copied: 1423764
writing to copied array: 2089496

Since PHP takes references of arrays by default there is little need to pass arrays around by reference in function paremeters.