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

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

To get an idea about the objects size, try

strlen(serialize($object));

It is by no means accurate, but an easy way to get a number for comparison.

Answer:

If you need to know the size of an already created object or array, you can use the following code to find it out.

<?php

function rec_copy($src) {
  if (is_string($src)) {
    return str_replace('SOME_NEVER_OCCURING_VALUE_145645645734534523', 'XYZ', $src);
  }

  if (is_numeric($src)) {
    return ($src + 0);
  }

  if (is_bool($src)) {
    return ($src?TRUE:FALSE);
  }
  if (is_null($src)) {
    return NULL;
  }

  if (is_object($src)) {
    $new = (object) array();
    foreach ($src as $key => $val) {
      $new->$key = rec_copy($val);
    }
    return $new;
  }

  if (!is_array($src)) {
    print_r(gettype($src) . "\n");
    return $src;
  }

  $new = array();

  foreach ($src as $key => $val) {
    $new[$key] = rec_copy($val);
  }
  return $new;
}

$old = memory_get_usage();
$dummy = rec_copy($src);
$mem = memory_get_usage();

$size = abs($mem - $old);
?>

This essentially creates a copy of the array structure and all of its members.

A not 100% accurate, but still working version is also:

<?php

$old = memory_get_usage();
$dummy = unserialize(serialize($src));
$mem = memory_get_usage();

$size = abs($mem - $old);

Hope that helps for cases where the object is already build.

Answer:

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.