Alex Rivera | Logout

Getting size in memory of an object in PHP?

Asked 2009-08-29T16:44:53.500
44

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.

Edit
Report

1 Answer

20

Would it not make sense to try serializing the object and reading the string length? Obviously it will be several bytes off because serialized string would have s:'string' therefore s:'' being extra bytes... unless serialize could be the same way that PHP stores objects???

so for example

$size = strlen(serialize($object));

Just a thought?

Another messy but possibly accurate thought:

Assuming a class instance variable that has been manipulated a few times since instantiation:

$DB; // database access class for eg.
$mem = memory_get_usage();
$DB_tmp = clone $DB;
$mem = memory_get_usage() - $mem;
unset($DB_tmp);

$mem could be the exact amount of memory allocated to $DB;

answered 2011-03-20T21:54:35.210

Your Answer