doudun8705 2011-02-18 00:41
浏览 60
已采纳

PHP性能问题:更快地将重复项留在将要搜索的数组中或执行array_unique?

I have code that adds values to an array. The array is later searched in another part of my code. The values that are added to the array are not necessarily unique, so it's possible to end up with duplicate values in the array being searched. Technically speaking, even with the duplicates present in the array being searched, my code works fine and I'll be able to find the value. I just want to know if the value is in the array being searched, and don't care if it's in the array 1 time or 10,000 times.

My question is whether it's preferred (for performance and/or style reasons) to do array_unique() on my array being searched before I do the search.

So for example, suppose I want to search an array like this:

$searchMe = Array("dog", "cat", "mouse", "dog", "dog", "dog");

Note that "dog" is present 4 times. If I want to search for the value "dog", in that array, it will work fine and I will be able to tell that it's present. As mentioned above, I don't care how many times it's present, I just want to know if it's present at all.

So should I do this first before searching and then search against the de-duped array?

$searchMe_cleaned = array_unique($searchMe);

I.e., will that be faster than just searching the array with the duplicates?

Please keep in mind that although in this example the array being searched just has a few elements, the real array being searched could have hundreds or thousands of elements.

Thanks!

  • 写回答

3条回答 默认 最新

  • doufeixuan8882 2011-02-18 00:45
    关注

    I think array_unique is slower than in_array but it makes sense if you want to search the array more than one time or if you want to save memory.

    Another option is to use array_flip (which will also drop duplicate keys) and then use isset or array_key_exists since they are way faster than in_array, personally I would go this way.

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探