duan1979768678 2013-08-12 00:08
浏览 61
已采纳

PHP数组内存使用情况

I am trying to find a way to map big amount of strings to ints. I tried it using arrays and found a behaviour that I don't understand. When I index arrays by strings (array('someStirng' => 1)) it consumes less memory than vice versa (array(1 => 'someString')). Does it mean, that it's better to index arrays by strings and leave ints as values for big amount of string-int pairs or what's the catch? Why there is so big memory allocation difference?

function gen() {
    static $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < 8; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

Indexing by strings - returns 490 KB

$a = array();

for($x = 0;$x < 100000;$x++){
    $a[gen()]  = $x;
}


echo (memory_get_usage() / 1024) . ' KB';

Indexing by ints - returns 10790.2890625 KB (~22 times more than first case, but same ammount of information stored!)

$a = array();

for($x = 0;$x < 100000;$x++){
    $a[$x]  = gen();
}


echo (memory_get_usage() / 1024) . ' KB';
  • 写回答

2条回答 默认 最新

  • douxia2137 2013-08-12 01:03
    关注

    When I repeat your experiments using your code, I get 18 072 000 bytes for the integer indexes and 16 471 960 bytes for the string indexes. Not much difference, which can be attributed to different memory management for array keys and their values.

    Using memory_get_peak_usage(true) instead produces very similar results. Calculating the difference in memory usage right before and right after the for loop, I get 18 087 936 bytes with integer indexes and 16 515 072 bytes with string indexes.

    That's a small difference which could be explained by different internal memory management for array keys and for array values. Perhaps since array keys are limited to scalars and array values aren't, PHP can optimize somewhere.

    In any case, like @ed-heal said, use the best data structure for whatever you're trying to do. The memory usage is probably not that important and if it is, PHP might not be the tool for the job.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 angular开发过程中,想要读取模型文件,即图1的335行,会报404错误(如图2)。但我的springboot里配置了静态资源文件,如图3。且在该地址下我有模型文件如图4,请问该问题该如何解决呢?
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。
  • ¥15 关于哈夫曼树应用得到一些问题