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

后端 未结 11 2404
有刺的猬
有刺的猬 2020-11-28 19:30

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.

11条回答
  •  庸人自扰
    2020-11-28 19:42

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

提交回复
热议问题