in_array vs isset-性能 [英] in_array vs isset - performance
问题描述
请考虑以下代码段:
示例1
$array = Array(1,2,3,4,5,6,7);
$array_test = Array(3,5,4,7,3,6,7,8,8,9,3);
foreach($array_test as $value) {
if(in_array($value, $array)) {
// do some magic here
}
}
示例2
$array = Array(1,2,3,4,5,6,7);
$array_test = Array(3,5,4,7,3,6,7,8,8,9,3);
$array_index = Array();
foreach($array as $value) {
$array_index[ $value ] = true;
}
foreach($array_test as $value) {
if(isset($array_index[ $value ])) {
// do some magic here
}
}
很明显,两个片段都执行相同的工作.在某些阵列样本中,示例1比示例2更快.
Obviously both snippets do the same jobs. In some array samples example #1 is faster than example #2.
我确定我们都处于这两种情况下,但是我的问题是:
I am sure we all were in both situations, however my question is:
- 我应该总是选择#2吗?
- 我何时应该选择#1?当
$ array * $ array_test
的大小为<时,10个?< 100?< 1000? - 如何确定在特定情况下哪种方法更好?
- 也许除了使用临时表
$ array_index
之外,还有其他技巧.我不记得其他编程语言中的类似情况,一切准备就绪
- Should I always choose #2?
- When should I choose #1? When size of
$array * $array_test
is < 10? <100? <1000? - How to determine which method is better in particular situation?
- Maybe there is some other trick than using temp table
$array_index
. I don't remember similar situation in other programming languages, everything was ready as-you-go
也请注意关联键.
有人已经问过非常类似的问题:
Someone already asked very similar question:
推荐答案
在第二个示例中,必须先构造 $ array
的翻转"值,然后才能使用 isset()
.顺便说一句,您也可以使用 array_flip()
.
In your second example, you have to construct the "flipped" value of $array
before you can use isset()
. Btw, you can also use array_flip()
for that.
如果您可以立即使用数组键(无需转换),请使用 isset()
,因为由于查找键的方式,它显然比 in_array()
快得多和,因为它是一种语言构造.
If you can use array keys immediately (without conversion), use isset()
because it's obviously much faster than in_array()
due to way keys are looked up and because it's a language construct.
如果不进行转换就无法使用键,则可以考虑将 in_array()
用于小型数组.对于更大的阵列,可能值得运行基准测试来确定是否仍然值得进行阵列转换.
If you can't use the keys without conversion, you could consider using in_array()
for small arrays. For bigger arrays it might be worthwhile to run a benchmark to determine whether an array conversion step would still be worth it.
最后,并且在很大程度上取决于情况,您也可以使用 array_intersect _
函数之一,主要是为了避免在PHP代码内部循环.
Lastly, and depending largely on the situation, you could use one of the array_intersect_
functions as well, mainly to avoid having to loop inside PHP code.
这篇关于in_array vs isset-性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!