PHP对象创建和内存使用 [英] PHP Object Creation and Memory Usage

查看:77
本文介绍了PHP对象创建和内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本的虚拟类:

class foo
{
    var $bar = 0;
    function foo() {}
    function boo() {}
}
echo memory_get_usage();
echo "\n";
$foo = new foo();
echo memory_get_usage();
echo "\n";
unset($foo);
echo memory_get_usage();
echo "\n";
$foo = null; 
echo memory_get_usage();
echo "\n";

输出:

$ php test.php
353672
353792
353792
353792

现在,我知道PHP文档说只有在需要内存时才释放内存(达到上限).但是,我将其编写为一个小测试,因为我要执行更长的任务,需要使用更大的对象以及该对象的许多实例.而且内存只是增加,最终用完并停止执行.即使这些大对象确实占用了内存,但由于我在按顺序处理完之后销毁了它们,所以它不应用完内存(除非单个对象耗尽了整个内存空间,事实并非如此) ).

Now, I know that PHP docs say that memory won't be freed until it is needed (hitting the ceiling). However, I wrote this up as a small test, because I've got a much longer task, using a much bigger object, with many instances of that object. And the memory just climbs, eventually running out and stopping execution. Even though these large objects do take up memory, since I destroy them after I'm done with each one (serially), it should not run out of memory (unless a single object exhausts the entire space for memory, which is not the case).

有想法吗?

推荐答案

以下是带有循环引用的修订示例:

Here's a revised example with circular references:

<?php
class foo
{
    public $bar = 0;
    function foo(){}
    function boo(){}
}

echo memory_get_usage() . "\n";

$foo = new foo();
unset($foo);

echo memory_get_usage() . "\n";

$arr = array(new foo());

for ($i = 1; $i < 1000000; $i += 2)
{
    $arr[$i] = new foo();
    $arr[$i - 1] = new foo();
    unset($arr[$i], $arr[$i - 1]);
}

echo memory_get_usage() . "\n";

for ($i = 1; $i < 1000000; $i += 2)
{
    $arr[$i] = new foo();
    $arr[$i - 1] = new foo();
    $arr[$i]->bar = $arr[$i-1];
    $arr[$i-1]->bar = $arr[$i];
    unset($arr[$i], $arr[$i - 1]);
}

echo memory_get_usage() . "\n";

使用PHP 5.3.6(cli)的输出:

Outputs with PHP 5.3.6 (cli):

644392
644392
644848
1628592

这篇关于PHP对象创建和内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆