Analysis of Memory Leak Caused by Recursive Reference of PHP Object

  • 2021-07-16 02:03:37
  • OfStack

Generally speaking, if there is a recursive reference to PHP object, there will be a memory leak. This Bug has existed in PHP for a long time. Let's reproduce this Bug first. The sample code is as follows:


<?php
class Foo {
  function __construct() {
    $this->bar = new Bar($this);
  }
}

class Bar {
  function __construct($foo) {
    $this->foo = $foo;
  }
}

for ($i = 0; $i < 100; $i++) {
  $obj = new Foo();

  unset($obj);
  echo memory_get_usage(), "/n";
}
?> 

Run the above code, and you will find that the memory usage should have been constant, but it is actually increasing, and unset is not fully effective.

Many of the current development is based on the framework, and there are complex object relationships in the application, so it is very likely to encounter such problems. Let's take a look at what expedient measures are there:


<?php
class Foo {
  function __construct() {
    $this->bar = new Bar($this);
  }

  function __destruct() {
    unset($this->bar);
  }
}

class Bar {
  function __construct($foo) {
    $this->foo = $foo;
  }
}

for ($i = 0; $i < 100; $i++) {
  $obj = new Foo();

  $obj->__destruct();
  unset($obj);
  echo memory_get_usage(), "/n";
}
?>

The method was ugly, but it was finally dealt with. Fortunately, this Bug has been fixed in the CVS code of PHP 5.3.

In this regard, it is necessary to pay attention when designing PHP program! I believe that this paper has a certain reference value for everyone's PHP programming.


Related articles: