Getting size in memory of an object in PHP?

前端 未结 5 1895
旧时难觅i
旧时难觅i 2020-12-09 08:09

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

5条回答
  •  没有蜡笔的小新
    2020-12-09 08:37

    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;

提交回复
热议问题