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

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

    In answer to Tatu Ulmanens answer:

    It should be noted, that $start_memory itself will take up memory (PHP_INT_SIZE * 8).

    So the whole function should become:

    function sizeofvar($var) {
        $start_memory = memory_get_usage();
        $var = unserialize(serialize($var));
        return memory_get_usage() - $start_memory - PHP_INT_SIZE * 8;
    }
    

    Sorry to add this as an extra answer, but I can not yet comment on an answer.

    Update: The *8 is not definate. It can depend apparently on the php version and possibly on 64/32 bit.

提交回复
热议问题