How much memory do PHP variables use?

Apr 12, 2014, by admin

There are cases when it might be quite important to know how much memory uses each variable in PHP script. The function memory_get_usage returns the amount of memory, in bytes, that’s currently being allocated to your PHP script.

The following script shows total allocated memory to your PHP script.

echo memory_get_usage();

In PHP, there is no special function to get the memory usage of a single variable. But you can use memory_get_usage function that will return the total amount of memory allocated to your PHP script as explained above and do a workaround and measure usage before and after to get the usage of a single variable.

The following script shows total memory usage of a single variable.

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);

Here we’ve a $tmp variable which assign $var to create a shallow copy to prevent memory allocation until $tmp is modified.

As we know that it’s not a reliable way as we can’t be sure that nothing else touches memory while assigning the variable, so this should only be used as an approximation.