Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

oop - Getting size in memory of an object in PHP?

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

EDIT:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...