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

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

    You could opt for calculating memory difference on a callback return value. It's a more elegant solution available in PHP 5.3+.

    function calculateFootprint($callback) {
        $startMemory = memory_get_usage();
        $result = call_user_func($callback);
        return memory_get_usage() - $startMemory;
    }
    
    $memoryFootprint = calculateFootprint(
        function() {
            return range(1, 1000000);
        }
    );
    
    echo ($memoryFootprint / (1024 * 1024)) . ' MB' . PHP_EOL;
    

提交回复
热议问题