• PHP对象递归引用造成内存泄漏


    如果PHP对象存在递归引用,就会出现内存泄漏。这个Bug在PHP里已经存在很久很久了,先让我们来重现这个Bug,代码如下:

    <?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";
    }
    ?>


    运行以上代码,你会发现,内存使用量本应该不变才对,可实际上却是不断增加,unset没有完全生效。

    现在的开发很多都是基于框架进行的,应用里存在复杂的对象关系,那么就很可能会遇到这样的问题,下面看看有什么权宜之计:

    <?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";
    }
    ?>


    办法有些丑陋,不过总算是对付过去了。幸运的是这个Bug在PHP5.3的CVS代码中已经被修复了。

  • 相关阅读:
    【poj2828】Buy Tickets
    【hdu2795】Billboard
    【hdu1394】Minimum Inversion Number
    【BZOJ1012】 【JSOI2008】最大数maxnumber
    【hdu】p1754I Hate It
    【线段树模板】
    Day1
    synchronized底层原理
    Java之浅拷贝和深拷贝
    图解算法——恢复一棵二叉搜索树(BST)
  • 原文地址:https://www.cnblogs.com/firstdream/p/2410081.html
Copyright © 2020-2023  润新知