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

后端 未结 11 2419
有刺的猬
有刺的猬 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:52

    I had a similar problem, and the solution I used was to write the variable to a file then run filesize() on it. Roughly like this (untested code):

    function getVariableSize ( $foo ) 
    {
        $tmpfile = "temp-" . microtime(true) . ".txt";
        file_put_contents($tmpfile, $foo);
        $size = filesize($tmpfile);
        unlink($tmpfile);
        return $size;
    }
    

    This solution isn't terribly fast because it involves disk IO, but it should give you something much more exact than the memory_get_usage tricks. It just depends upon how much precision you require.

提交回复
热议问题