Give you two arrays with 5,000 elements, and calculate their difference, which is the Array_diff algorithm implemented with PHP and the best algorithm you think.
The first time I received this topic, I found it very simple, so according to previous experience wrote one:
function Array_diff ($array _1, $array _2) { $diff = array (); foreach ($array _1 as $k = = $v 1) { $flag = false; foreach ($array _2 as $v 2) { if ($flag = ($v 1 = = $v 2)) {break ; } } if (! $flag) { $diff [$k] = $v 1; } } return $diff; }
Although the implementation is possible, the efficiency of this function is found to be appalling. So I reconsidered and optimized the algorithm, and the second function looks like this:
function Array_diff ($array _1, $array _2) { foreach ($array _1 as $key + $item) { if (In_array ($item, $array _2 , true) { unset ($array _1[$key]);} } return $array _1; }
Well, this time it's almost comparable to the speed of the original Array_diff function. But is there any way to optimize it? From an article on Chinaunix, I found that PHP could have written this way:
function Array_diff ($array _1, $array _2) { $array _2 = Array_flip ($array _2); foreach ($array _1 as $key = + $item) { if (isset ($array _2[$item]) { unset ($array _1[$key]); } } return $array _1; }
This function is surprisingly efficient, even faster than the original Array_diff function. For the reasons, I found the explanation: Because the keys are organized in a HASH, the lookup is quick, and Value is stored by the key organization, and it is not indexed by itself, and each lookup is traversed.
Summarize
While this is a small trick of the PHP language, it is much more efficient to iterate over and contrast the values of the array than the normal value if it is necessary to reverse the value by comparing it to the key.
For example, the function two above needs to call the In_array function needs to loop to determine whether the function inside, and the function of the three only to determine whether the array exists the key is OK. With the array key and the value of the organization index of the different way, more efficient than the imagination that is very understandable.