PHP性能问题:更快地将重复项保留在将要搜索的数组中,或者做array_unique吗? [英] PHP Performance question: Faster to leave duplicates in array that will be searched or do array_unique?

查看:105
本文介绍了PHP性能问题:更快地将重复项保留在将要搜索的数组中,或者做array_unique吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有将值添加到数组的代码.稍后在我的代码的另一部分中搜索该数组.添加到数组中的值不一定是唯一的,因此最终可能会在要搜索的数组中出现重复的值.从技术上讲,即使正在搜索数组中存在的重复项,我的代码也可以正常工作,并且我将能够找到该值.我只想知道该值是否在要搜索的数组中,而不管它在数组中是1次还是10,000次.

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.

我的问题是(出于性能和/或样式方面的原因)在进行搜索之前是否优先对要搜索的数组执行array_unique().

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.

因此,例如,假设我要搜索这样的数组:

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

请注意,狗"出现了4次.如果我想在该数组中搜索值"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.

所以我应该先搜索然后再对重复数据删除的数组进行搜索吗?

$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.

谢谢!

推荐答案

我认为array_unique的速度比in_array慢,但是如果要多次搜索数组还是要节省内存,这是有道理的

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.

另一种选择是使用 array_flip (也会删除重复的键),然后使用issetarray_key_exists,因为它们比in_array快得多,我个人将采用这种方式.

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.

这篇关于PHP性能问题:更快地将重复项保留在将要搜索的数组中,或者做array_unique吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆