BitOne / php-meminfo

PHP extension to get insight about memory usage
MIT License
1.08k stars 78 forks source link

What you mean under "forever in memory"? #58

Closed Shkarbatov closed 6 years ago

Shkarbatov commented 6 years ago

Hi, trying to understand this slide: https://speakerd.s3.amazonaws.com/presentations/8f6d8303502241cab85a320a2bb1db2d/slide_27.jpg

What you mean under "forever in memory"?

If I try next:

class MyClass{}

function buildObjects() {
    $objectA = new MyClass();
    $objectB = new MyClass();

    $objectA->b = $objectB;
    $objectB->a = $objectA;

    return $objectA;
}

$leakHolder = [];
for ($i = 0; $i < 200; $i++) {

    $object = buildObjects();
    $leakHolder[] = $object;
}

unset($leakHolder);
unset($object);
meminfo_dump(fopen('/tmp/php_mem_dump'.$i.'.json','w'));

With iterations: 200, 2 000, 20 000, 200 000


Result always the same:

| Type    | Instances Count | Cumulated Self Size (bytes) |
+---------+-----------------+-----------------------------+
| string  | 82              | 4643                        |
| array   | 9               | 648                         |
| integer | 4               | 64                          |
| unknown | 2               | 32                          |
| float   | 1               | 16                          |
+---------+-----------------+-----------------------------+

What you mean under "always stay in memory"?

As I understand memory will leak until not start cycle GC or until I not run gc_collect_cycles(). We can find only what developer forget to unset.

BitOne commented 6 years ago

This slide explains that without a garbage collector for cycling reference, the objects would stay forever in memory. That was the behavior of pre PHP 5.3, when only the reference counter was managing the memory.

Now we have the GC, this will not happen unless you have a real memory leak.