How to determine the memory footprint (size) of a variable?

There’s no direct way to get the memory usage of a single variable, but as Gordon suggested, you can use memory_get_usage. That will return the total amount of memory allocated, so you can use a workaround and measure usage before and after to get the usage of a single variable. This is a bit hacky, but it should work.

$start_memory = memory_get_usage();
$foo = "Some variable";
echo memory_get_usage() - $start_memory;

Note that this is in no way a reliable method, you can’t be sure that nothing else touches memory while assigning the variable, so this should only be used as an approximation.

You can actually turn that to an function by creating a copy of the variable inside the function and measuring the memory used. Haven’t tested this, but in principle, I don’t see anything wrong with it:

function sizeofvar($var) {
    $start_memory = memory_get_usage();
    $tmp = unserialize(serialize($var));
    return memory_get_usage() - $start_memory;
}

Leave a Comment