down00111 2011-07-09 19:23
浏览 37
已采纳

PHP中的数组查找速度; 长缓存键

I'm working on a method that, due to the expense of it's operation and frequency which it is called with identical arguments, would benefit from caching the return values.

I'll be serialize()-ing the arguments together for cache keys, but this can result in very long keys, due to the lengthy array arguments.

  • Does PHP array indexing and look-up suffer from such long keys (think from 250B to 1kB+)?
  • So far so good, but am I facing a situation where this could fail spectacularly on me at some point?
  • Basically, should I md5() (or alternative) the keys?

Minor clarifications:
This is only per-request caching, with no permanent storage. The method in question is that of a view helper, and for each view generation it may be called 500 times or more.

  • 写回答

2条回答 默认 最新

  • dqhgjay5753 2011-07-09 19:34
    关注

    You should definitely hash the key. You would maybe say "Why should i risk getting collisons when i can concatenate at every point of time a unique key?". The easy answer is if you generate cache keys via string concatenation you have to calculate always with the worst case of space requirements to estimate ram usage.

    So if you have a cache with 200 entries .. and 2 fields with 20character max strings. The worst case would be 200*2*20*(size of character). If you load the complete cache on every possible parallel connection this will multiply by the amount of parallel connections.

    With hashes you always have the minimum ram requirement = maximum ram requirement for the key field.

    If you have many values which are concatenated for the keys this will scale very bad.

    Edit:

    Even if you use it per request the array consumes memory. Though it is a cache it is present from the beginning to the end of the request. So you need to take into account that it consumes a certain amount of space in your memory and while using a hash its a fixed amount.

    The second thing is that keys need to be compared. If you access an associative array with a string key your interpreter needs to compare the key charwise. If you have a hash method for generating keys this will be also a fixed number of steps.

    If you use concatenation the amount of steps will range between the best and the worst case.

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

报告相同问题?

悬赏问题

  • ¥60 求会做山景bo1048b2程序的 直播声卡用
  • ¥15 51单片机与数码管实现电子琴
  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错