您的问题无法轻易回答,因为确切的内存占用取决于几个因素,我将尝试在下面概述其中的一些因素。
如果您只需要一些快速的数字,请考虑:
PHP 在内部将值存储在 structure called the zval:
121 struct _zval_struct {
122 zend_value value; /* value */
123 union {
124 struct {
125 ZEND_ENDIAN_LOHI_4(
126 zend_uchar type, /* active type */
127 zend_uchar type_flags,
128 zend_uchar const_flags,
129 zend_uchar reserved) /* call info for EX(This) */
130 } v;
131 uint32_t type_info;
132 } u1;
133 union {
134 uint32_t var_flags;
135 uint32_t next; /* hash collision chain */
136 uint32_t cache_slot; /* literal cache slot */
137 uint32_t lineno; /* line number (for ast nodes) */
138 uint32_t num_args; /* arguments number for EX(This) */
139 uint32_t fe_pos; /* foreach position */
140 uint32_t fe_iter_idx; /* foreach iterator index */
141 } u2;
142};
这是一个联合类型,意味着它可以存储多种类型的值。所以是的,它保留了额外的数据来提醒自己它是什么。整数通常表示为 long(32 位或 64 位,具体取决于您的平台)。
关于数组,有一个excellent blog post by NikiC给出了详细的解释。要点:
| 64 bit | 32 bit
---------------------------------------------------
zval | 24 bytes | 16 bytes
+ cyclic GC info | 8 bytes | 4 bytes
+ allocation header | 16 bytes | 8 bytes
===================================================
zval (value) total | 48 bytes | 28 bytes
===================================================
bucket | 72 bytes | 36 bytes
+ allocation header | 16 bytes | 8 bytes
+ pointer | 8 bytes | 4 bytes
===================================================
bucket (array element) total | 96 bytes | 48 bytes
===================================================
total total | 144 bytes | 76 bytes
上述数字会因您的操作系统、编译器和编译选项而异。例如。如果你用调试或线程安全编译 PHP,你会得到不同的数字。但我认为上面给出的大小是您在 Linux 上 PHP 5.3 的平均 64 位生产构建中看到的。
还值得注意的是,非数字数组键标签也是一种分配,因此标签越长,它们消耗的内存显然就越多。
上面的数字还取决于您使用的 PHP 版本。由于 Zend 引擎的内部更改,PHP >= 7 的内存占用应该远低于任何 PHP
有关更多信息,另请参阅这些资源: