Get variable current memory space in PHP
SO,
The problem
I have need in determining variable space used in script in certain
moment. The variable is normal PHP variable - so it can be anything
(array, object, resource e t.c.). As a result i want some function - let
it be called getMemorySpace - and should return integer value as a number
of bytes, which are used for variable in current moment.
My approach
I know that the easiest way to do this is to use memory_get_usage() with
combination of unset() and copying variable (and, probably,
gc_collect_cycles()). But this method has a serious problem: imagine that
we have X Mbytes memory limitation for our script and checked variable, of
cause, fit this requirement. If we'll try to act as described above with
memory_get_usage() - we'll face a problem for all variables that are
larger than X/2, cause first we need to copy our variable (before
destroying it). So, such way will result it memory overflow.
Specifics
As I've searched from google (which actually is a front-end for SO in such
cases) - get memory space is a problem in PHP with native methods. For
example, if we have an array, then one of solutions is to walk recursively
and gather information about element's size (that would be strlen() for
strings and standard sizes for other data types).
But the problem is more complicated since I want to know that size even if
it's object, callback or even resource. In fact, approximately (but
precise till corresponding unit - for example, if we're measuring in
Mbytes, than it should be +/- 1Mbyte in result) solution will also be good
- but I have no clue - how to do this in other way that those described
above. This is the only reason I've not provided any PHP code.
I'm using PHP 5.5 and so answer could rely on that (if it matters).
No comments:
Post a Comment