PHP:对象数组和内存泄漏


PHP: Array of objects and memory leak

在从对象数组导出大量文件期间,我遇到了内存泄漏问题。简化后的代码如下所示:

class Test_Class
{
    private $a = null;
    public function __construct($a = null)
    {
        $this->a = $a;
    }
    public function __destruct()
    {
        unset($this->a);
    }
}
print 'Memory before: '.memory_get_usage(1).' <br>'; // 262 144 
$a = [];
for ($i=0; $i<600000; $i++)
    $a[] = new Test_Class($i);
print 'Memory after create: '.memory_get_usage(1).' <br>'; // 129 761 280 
for($i=0; $i < count($a); $i++)
    unset($a[$i]);
unset($a);
print 'Memory after: '.memory_get_usage(1).' <br>'; // 35 389 440 

在下一次迭代时,内存仍然结束。知道如何释放占用的内存吗?

注:我尝试unset()/assign null和gc_collect_cycles(),没有一个方法允许我释放被对象数组占用的内存

我不认为这是内存泄漏。内存是真正释放和可用的,似乎php保留它供自己使用,而不是把它还给系统。我猜这和垃圾收集器有关。这似乎是一种不好的行为,但也许有一个很好的理由……

她是我的证据:(由于我的配置,我使用较小的值,但行为是相同的)

/*
   You class definition
*/
print 'Memory before: '.memory_get_usage(1).' <br>'; // 262 144 
$a = [];
$b = [];
for ($i=0; $i<5000; $i++)
    $a[] = new Test_Class($i);
print 'Memory after create: '.memory_get_usage(1).' <br>'; // 2 359 296 
for($i=0; $i < count($a); $i++)
    unset($a[$i]);
unset($a);
print 'Memory after unset: '.memory_get_usage(1).' <br>'; // 1 572 864 
for ($i=0; $i<1000; $i++)
    $b[] = $i;
print 'Memory after $b: '.memory_get_usage(1).' <br>'; // 1 572 864 

您可以在这里看到$b的创建不需要任何更多的内存。这很奇怪,因为当你之前没有做任何事情时,数组需要内存:

$b = [];
print 'Memory before: '.memory_get_usage(1).' <br>'; // 262 144 
for ($i=0; $i<1000; $i++)
    $b[] = $i;
print 'Memory after: '.memory_get_usage(1).' <br>'; // 524 288 

这就是为什么我认为内存被释放了,但php只是坐在它上面