【问题标题】:How much memory does a variable with int value require in PHP?PHP中具有int值的变量需要多少内存?
【发布时间】:2015-03-26 06:29:24
【问题描述】:

我知道,这个问题之前可能已经被问过几次,但我已经阅读了这里所有类似的问题和所有答案,但仍然不明白。所以,我的脚本中有一个变量声明:

$a = 255;

这个变量需要多少内存?我读过this excellent article,它解释了将为内部PHP 结构分配多少内存(例如_zval_struct_zval_gc_info_zend_mm_block_info)。结果是48 字节。但在我的机器上,我得到了168 字节。他们来自哪里?我通过在声明前后调用memory_get_usage() 得到这个号码。

我在 Mac OS X 上运行 PHP 5.5.18(64 位)。

提前致谢。

【问题讨论】:

  • 32 位 PHP 还是 64 位 PHP?但是 32 位 28 字节和 64 位 PHP 56 字节
  • 请注意,PHP 内存不是以字节为单位分配的,而是以块为单位的,因此仅通过测量分配前后的内存使用情况不太可能得到准确的数字
  • @MarkBaker memory_get_usage(true) 函数(注意true 参数)将返回所有块的大小。
  • 那么你需要一个外部内存分析器。 XDebug 曾经有,但他们放弃了它。 github 上有一个 php-memory-profiler 库,效果更好:github.com/arnaud-lb/php-memory-profiler

标签: php-5.5 php-internals


【解决方案1】:

因此,感谢 Sergiu Paraschiv 的评论,我安装了memprof 并对该主题进行了小型研究。这是我在 Mac 上使用 PHP 5.5.18(64 位)得到的结果:

<?php
memprof_enable();

$a = 255;           // +104 (+32 for smth initial?), total: 136
$b = 255;           // +104, total: 240
$c = 255.5;         // +104, total: 344
$d = 'h';           // +104, total: 448
$e = [];            // +176, total: 624
$f = new stdClass;  // +136, total: 760
$g = $f;            // +72, total: 832
$h = $g;            // +72, total: 904
$i = $a;            // +72, total: 976
$j = &$i;           // +104, total: 1080
$k = &$j;           // +72, total: 1152  why not 104?
$l = &$h;           // +104, total: 1256
$m = null;          // +104, total: 1360
$n = true;          // +104, total: 1464

print_r(memprof_dump_array());

Array (
[memory_size] => 1464
[blocks_count] => 27
[memory_size_inclusive] => 1464
[blocks_count_inclusive] => 27
[calls] => 1
[called_functions] => Array
    (
        [memprof_dump_array] => Array
            (
                [memory_size] => 0
                [blocks_count] => 0
                [memory_size_inclusive] => 0
                [blocks_count_inclusive] => 0
                [calls] => 1
                [called_functions] => Array
                    (
                    )

            )

    )
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多