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: