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.
The count() function is used to count the elements of an array or the properties of an object. Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.
getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes.
PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier. The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets.
php $memory_limit = ini_get('memory_limit'); if (preg_match('/^(\d+)(.)$/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With