未使用的类常量会消耗内存吗?

时间:2019-06-04 17:54:46

标签: php

想象一下带有两个常量的此类

class Myclass
{
    const FOO = array (...) // ~50M data in here
    const BAR = array (...) // also ~50M data in here
}

a)

$foo=Myclass::FOO;
$bar=Myclass::BAR;

b)

$foo=Myclass::FOO;

在a)中,我同时调用了两个常量,我猜这将导致大约100M的内存使用。对?

在情况b)中,我只使用其中一个常量。内存使用量是100M还是50M?

2 个答案:

答案 0 :(得分:0)

100 MB。无论是否在后续代码中使用常量,每个类(而不是类实例)在编译时都会生成一次常量。这就是为什么它们必须是标量值的原因。您可以在PHP手册中阅读更多内容: PHP - Class Constants PHP - Class Constant Syntax

答案 1 :(得分:0)

以下功能将返回您的内存消耗。如果将TRUE传递给它,它将返回系统使用的内存消耗。如果通过FALSE,它将仅显示您的内存消耗。这将帮助您进一步测试问题。我现在无法进行测试以为您提供目前所需的确切答案,但是此功能非常通用。不仅会提供这种帮助,而且会提供更多帮助。

public static function GetMemoryUsage($System) 
{ 
        $mem_usage = memory_get_usage($System); 
        if ($mem_usage < 1024) $mem_usage = $mem_usage." B"; 
        elseif ($mem_usage < 1048576) $mem_usage = round($mem_usage/1024,2)." KB"; 
        else $mem_usage = round($mem_usage/1048576,2)." MB"; 
        return $mem_usage; 
    }