Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. <pre>
  2. <?php
  3.  
  4. // copy on write in php
  5.  
  6. // references:
  7. // http://php.net/manual/en/features.gc.php
  8. // http://www.tuxradar.com/practicalphp/18/1/11
  9.  
  10. function echoMemUsage() {
  11.     echo round((float)memory_get_usage()/1048576, 2)." MB\n";
  12. }
  13.  
  14. echoMemUsage(); // 0.08 MB
  15.  
  16. // declare a long string
  17. $str_a = str_repeat("helloworld", 100000);
  18.  
  19. echoMemUsage(); // 1.03 MB
  20.  
  21. // str_b is only given a reference to str_a
  22. $str_b = $str_a;
  23.  
  24. echoMemUsage(); // 1.03 MB
  25.  
  26. // str_b is `modified' and COW comes in
  27. $str_b = $str_b."";
  28.  
  29. echoMemUsage(); // 1.99 MB
  30.  
  31. // remove str_b from memory
  32. // note that mem usage decrease
  33. unset($str_b);
  34.  
  35. echoMemUsage(); // 1.03 MB
  36.  
  37. // -----------------------------------------
  38. // before php 5.3.0
  39.  
  40. $z = array();
  41. $z[0] = $str_a;
  42. $z[1] = &$z; // reference to itself
  43. unset($str_a);
  44.  
  45. echoMemUsage(); // 1.03 MB
  46.  
  47. unset($z);
  48.  
  49. echoMemUsage(); // 1.03 MB
  50.  
  51. // at this stage, we have unset all variables
  52. // but there is a memory leak!
  53.  
  54. ?>
  55. </pre>