PHP uses copy-on-write. It attempts to avoid physically copying data unless it needs to.
From PHP docs - Introduction to Variables:
PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.
You can test this easily:
/* memory usage helpers */
$mem_initial = memory_get_usage();
$mem_last = $mem_initial;
$mem_debug = function () use ($mem_initial, &$mem_last) {
$mem_current = memory_get_usage();
$mem_change = $mem_current - $mem_last;
echo 'Memory usage change: ', $mem_change >= 0 ? '+' : '-', $mem_change, " bytes\n";
$mem_last = $mem_current;
};
/* test */
echo "Allocating 10kB string\n";
$string = str_repeat('x', 10000);
$mem_debug();
echo "\n";
echo "Copying string by direct assignment\n";
$string2 = $string;
$mem_debug();
echo "\n";
echo "Modyfing copied string\n";
$string2 .= 'x';
$mem_debug();
echo "\n";
echo "Copying string with a (string) cast\n";
$string3 = (string) $string;
$mem_debug();
Output for PHP 5.x:
Allocating 10kB string
Memory usage change: +10816 bytes
Copying string by direct assignment
Memory usage change: +56 bytes
Modyfing copied string
Memory usage change: +10048 bytes
Copying string with a (string) cast
Memory usage change: +10104 bytes
- direct assignment doesn't copy the string in memory as expected
- modifying the copied string does duplicate the string in memory - copy-on-write has happened
- assigning the string with an additional
(string)
cast seems to duplicate the string in memory even if it is unchanged
Output for PHP 7.0:
Allocating 10kB string
Memory usage change: +13040 bytes
Copying string by direct assignment
Memory usage change: +0 bytes
Modyfing copied string
Memory usage change: +12288 bytes
Copying string with a (string) cast
Memory usage change: +0 bytes
- copy-on-write behavior is the same as in the 5.x versions but meaningless
(string)
casts don't cause the string to be duplicated in memory