Very fast array_unique

This URL provides a relatively faster array_unique alternative. I have worked a little on this and found the sugested function to be very helpful.

The author worked with the array that had keys integers and values strings. I checked the same scenerio and it was about 40% faster. Then i used integers in values of array and surprised to see performance of the suggested function. Its about 9x faster. If you dont believe me test it yourself.


Try these two tests:


for( $a=1; $a<=50; $a++ )
{
    $ar[]    = mt_rand( 0 , 5 );
}

function fast_unique($input) {
    return array_flip(array_flip(array_reverse($input,true)));
}

$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = fast_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";


$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = array_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";




And the second test:


for( $a=1; $a<=50; $a++ )
{
    $ar[]    = (string) mt_rand( 0 , 5 );
}




function fast_unique($input) {
    return array_flip(array_flip(array_reverse($input,true)));
}

$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = fast_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";


$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = array_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";



In the first test, the performance is 9x, in the second, it is just 40% faster. A really considerable difference if your application needs a lot of arrays sorting like work.