有没有一种方法可以估计PHP数组将消耗多少内存


Is there a way to estimate how much memory will PHP array consume?

假设您有一个查询,并且您确切地知道它将返回多少结果以及每列的长度,例如1M记录int `id`, char(100) `uid`

有没有办法提前知道PHP需要为这个关联数组分配多少内存?

只是不要将1M记录分配为关联数组。只选择您需要的数据。

找到答案的最佳方法是执行以下操作:

$numItems = 1000000;
$bytes = memory_get_usage();
$arr = array();
$arrBytes = memory_get_usage() - $bytes;
$arr[] = array('id'=>1,'uid'=>str_repeat("a",100));
$itemBytes = memory_get_usage() - $bytes - $arrBytes;
echo "Total memory usage estimate: ".($arrBytes + ($itemBytes * $numItems));

免责声明:我不完全确定这会有多准确,但应该给出一个大概值。这在不同的系统(即32位整数与64位整数)和不同的编码(即单字节与多字节)上也会有所不同。

说到这里(正如@YourCommonSense所指出的)。"一个百万项数组将消耗多少内存"的答案是"太多"。考虑分页或类似的方式来减少您需要的项目数量。