How to find memory used by an object in PHP? (sizeof)

Viewed 49503

How to find memory used by an object in PHP? (c's sizeof). The object I want to find out about is a dictionary with strings and ints in it so it makes it hard to calculate it manually. Also string in php can be of varied length depending on encoding (utf8 etc) correct?

6 Answers

You could use memory_get_usage().

Run it once before creating your object, then again after creating your object, and take the difference between the two results.

This method converts the array to a json string and determines the length of that string. The result should be fairly similar to the size of the array (both will have delimiters to partition members of the array or the stringified json) strlen(json_encode(YourArray))

this method could be help you:

function getVariableUsage($var) {
 $total_memory = memory_get_usage();
 $tmp = unserialize(serialize($var));
 return memory_get_usage() - $total_memory; 
}

$var = "Hey, what's you doing?";
echo getVariableUsage($var);

https://www.phpflow.com/

I don't know that there is a simple way to get the size of an object in PHP. You might just have to do an algorith that

  1. Counts the ints
  2. Multiplies number of ints by size of an int on hard disk
  3. Convert characters in strings to ASCII and
  4. Multiply the ASCII values by how much they take up on disk

I'm sure there is a better way, but this would work, even though it would be a pain.

Related