在PHP中获取对象内存的大小? [英] Getting size in memory of an object in PHP?

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

问题描述

有一种方法可以获取PHP正在使用的总内存(memory_get_usage()),但是如何获取单个对象的内存大小呢?

There is a way to get the total memory PHP is using (memory_get_usage()) but how does one get the size in memory of an individual object?

我显然不是在谈论count(),因为我想要一个潜在的复杂数据结构中的字节数.

I'm obviously not talking about count() as I want the number of bytes in a potentially complex data structure.

推荐答案

您可以在分配类之前和之后调用memory_get_usage(),如

You can call memory_get_usage() before and after allocating your class as illustrated in this example from IBM. You could even create a wrapper to do this, possibly storing the result on a member variable of the complex class itself.

要弄清有关存储分配的内存大小的部分,您可以执行以下操作:

To clarify the part about storing the allocated memory size, you can do something like this:

class MyBigClass
{
    var $allocatedSize;
    var $allMyOtherStuff;
}

function AllocateMyBigClass()
{
    $before = memory_get_usage();
    $ret = new MyBigClass;
    $after = memory_get_usage();
    $ret->allocatedSize = ($after - $before);

    return $ret;
}

在将来的任何时候,您都可以检查allocateSize来查看该对象在分配时的大小.但是,如果在分配后添加到它,则allocateSize将不再准确.

At any point in the future, you could check allocatedSize to see how big that object was at time of allocation. If you add to it after allocating it, though, allocatedSize would no longer be accurate.

这篇关于在PHP中获取对象内存的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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