<pre>
<?php
// copy on write in php
// references:
// http://php.net/manual/en/features.gc.php
// http://www.tuxradar.com/practicalphp/18/1/11
function echoMemUsage() {
echo round((float)memory_get_usage()/1048576, 2)." MB\n";
}
echoMemUsage(); // 0.08 MB
// declare a long string
$str_a = str_repeat("helloworld", 100000);
echoMemUsage(); // 1.03 MB
// str_b is only given a reference to str_a
$str_b = $str_a;
echoMemUsage(); // 1.03 MB
// str_b is `modified' and COW comes in
$str_b = $str_b."";
echoMemUsage(); // 1.99 MB
// remove str_b from memory
// note that mem usage decrease
unset($str_b);
echoMemUsage(); // 1.03 MB
// -----------------------------------------
// before php 5.3.0
$z = array();
$z[0] = $str_a;
$z[1] = &$z; // reference to itself
unset($str_a);
echoMemUsage(); // 1.03 MB
unset($z);
echoMemUsage(); // 1.03 MB
// at this stage, we have unset all variables
// but there is a memory leak!
?>
</pre>