The difference of PHP array traversal (implementation of array_diff)
the following topic:
give you two arrays of 5000 elements respectively, calculate their difference set
- that is, the algorithm that uses PHP and the best algorithm that you think is the best algorithm.
first received the topic, and I found it very simple, so I wrote a "
[code]function array_diff", "{
$diff = array." Flag = false;
foreach ($array_2 as $v2) {
if ($flag = = > > > > = = > = > > > > > > > > > > > > > > > > > > > > > }
}
return $diff;
}[/code]
although it is possible, it is disastrous to find the efficiency of this function. Then I reconsidered and optimized the algorithm, and the second functions look like this:
[code]function array_diff ($array_1, $array_2) {
foreach ($array_1 as $key). ET ($array_1.#91; $key.#93;);
}
}
return / > well, this time it is almost as fast as the original function. But is there a better way to do it? By an article on ChinaUnix (embarrassed, cheating), I found that PHP can write this:
[code]function array_diff ($array_1, $array_2) {
$array_2 = array_flip. Rray_2.#91; $item.#93;)) {
unset ($array_1.#91; $key.#93;);
}
this function is very efficient, even faster than the original function. For the reason, I found the explanation:
because the key is the HASH organization, lookup quickly;
and Value is only stored by the Key organization, itself has no index, each lookup is traversal.
summing up
this is a trick of the PHP language, but it is much more efficient to compare the values of the comparison array with the value of the key in the values of the traversal and contrast array.
for example, the function two above needs to call the in_array function to circulate to judge whether it is within the function; and the function three can only judge whether the array has the key. With array key and different index of organization index, efficiency is higher than imagination, which is very understandable.