note 68949 deleted from function.array-unique by danbrown
| From: | danbrown@php.net | Date: | Thu, 06 Nov 2008 15:03:33 +0000 |
| Subject: | note 68949 deleted from function.array-unique by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-146224@lists.php.net to get a copy of this message | ||
Note Submitter: jacob dot bates at gmail dot com
----
In response to muddmonkey's flip-flip method, i would like to note that using this method as-is
leaves the array with gaps. For example, if we have an array like this:
Array
(
[0] => 1
[1] => 1
[2] => 1
)
And you apply the flip-flip method, you get this:
Array
(
[2] => 1
)
If you apply the array_merge function to the result, it closes these gaps without seriously
sacrificing performance. I wrote some test code that would result in a unique array that has 10,000
elements so that the impact of array_merge was more evident. Here is my test code:
function microtime_float(){ //timing (stolen from muddmonkey)
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//make an array and fill it up
$final=array();
for($i=0;$i<50000;$i++){
$final[]=$i%10000; //make sure the unique array has 10000 elements
}
//try flip-flip
$start1 = microtime_float();
array_flip(array_flip($final));
$stop1=microtime_float();
echo($stop1-$start1.' (flip-flip)<br>');
//try my flip-flip-merge
$start2=microtime_float();
array_merge(array_flip(array_flip($final)));
$stop2=microtime_float();
echo($stop2-$start2.' (flip-flip-merge)<br />');
//try array_unique
$start3=microtime_float();
array_unique($final);
$stop3=microtime_float();
echo($stop3-$start3.' (array_unique)<br />');
Here was the result:
0.14240193367004 (flip-flip)
0.18947601318359 (flip-flip-merge)
3.7108051776886 (array_unique)
As you can see, flip-flip-merge slows it down a little, but both are still way faster than
array_unique.