Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting size in memory of an object in PHP?

Tags:

object

oop

php

size

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.

like image 423
Artem Russakovskii Avatar asked Aug 29 '09 16:08

Artem Russakovskii


People also ask

How do I count the length of a object in PHP?

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.

How do you find the size of an object in a byte?

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.

How does PHP manage memory?

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.

How can I limit my PHP memory?

php $memory_limit = ini_get('memory_limit'); if (preg_match('/^(\d+)(.)$/


1 Answers

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.

like image 88
Eric J. Avatar answered Sep 30 '22 17:09

Eric J.