tags:

views:

219

answers:

4

Is there a function in PHP (or a PHP extension) to find out how much memory a given variable uses? sizeof just tells me the number of elements/properties.

EDIT: memory_get_usage helps in that it gives me the memory size used by the whole script. Is there a way to do this for a single variable?

+2  A: 

See:

Note that this won't give you the memory usage of a specific variable though.

You could also have a look at the PECL extension Memtrack, though the documentation is a bit lacking, if not to say, virtually non-existent.

Gordon
Yes. It can be used indirectly to answer the question.
Notinlist
+2  A: 

No, there is not. But you can serialize($var) and check the strlen of the result for an approximation.

Aistina
+4  A: 

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 = $var;
    return memory_get_usage() - $start_memory;
}
Tatu Ulmanen
`$tmp = $var` will create a shallow copy. This will not allocate more memory until $tmp is modified.
Gordon
@Gordon, you're right, I kinda overlooked that point. As I cannot figure out a proper way to modify the variable without changing it's type or size, I'll leave that be. Perhaps someone can come up with a proper idea :)
Tatu Ulmanen
@Tatu how about `$tmp = unserialize(serialize($var))`; This would combine Aistina's approach above.
Gordon
@Tatu also, since `$var` is already a shallow copy or reference of what was passed to the function, you don't need `$tmp`, but can reassign to `$var`. This saves the internal reference from `$tmp` to `$var`.
Gordon
A: 

Never tried, but Xdebug traces with xdebug.collect_assignments may be enough.

Arkh