简体   繁体   中英

in_array vs isset - performance

Consider following snippets of code:

Example #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
   }
}

Example #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
   }
}

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:

  • 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

Please mind about associative keys too.

Someone already asked very similar question:

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.

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.

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.

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.

isset will always be faster than in_array because keys are unique and values are not. The fact that keys are unique give optimization possibilities that are impossible with values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM