Last active
December 12, 2015 16:12
-
-
Save lav45/efed1e93948cd8369699 to your computer and use it in GitHub Desktop.
benchmark array_unique() vs \yii\helpers\ArrayHelper::unique()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* ~$ php -v | |
* PHP 7.0.0-5+deb.sury.org~trusty+1 (cli) ( NTS ) | |
* Copyright (c) 1997-2015 The PHP Group | |
* Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies | |
* with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies | |
* | |
* ~$ php test.php | |
* array_unique($arr) to 666667 in 1.4365818500519 | |
* foreach + array_keys to 666667 in 0.050886869430542 | |
* ArrayHelper::unique($arr) to 666667 in 0.034323215484619 | |
* ArrayHelper::unique($arr, true) to 666667 in 0.041811943054199 | |
*/ | |
class ArrayHelper | |
{ | |
public static function unique($array, $keepKeys = false) | |
{ | |
if ($keepKeys === false) { | |
$result = array_keys(array_flip($array)); | |
} else { | |
$result = array_flip(array_flip($array)); | |
} | |
return $result; | |
} | |
} | |
$max = 10000; | |
$arr = array_merge(range(1, $max, 3), range(1, $max, 2)); | |
$time = -microtime(true); | |
$res = array_unique($arr); | |
$time += microtime(true); | |
echo "array_unique(\$arr) to " . count($res) . " in " . $time . "\n"; | |
$time = -microtime(true); | |
$res = []; | |
foreach ($arr as $key => $val) { | |
$res[$val] = true; | |
} | |
$res = array_keys($res); | |
$time += microtime(true); | |
echo "foreach + array_keys to " . count($res) . " in " . $time . "\n"; | |
$time = -microtime(true); | |
$res = ArrayHelper::unique($arr); | |
$time += microtime(true); | |
echo "ArrayHelper::unique(\$arr, false) to " . count($res) . " in " . $time . "\n"; | |
$time = -microtime(true); | |
$res = ArrayHelper::unique($arr, true); | |
$time += microtime(true); | |
echo "ArrayHelper::unique(\$arr) to " . count($res) . " in " . $time . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$max = 10;
ArrayHelper::unique($arr, true) is winner
$max = 100;
ArrayHelper::unique($arr, true) is winner
$max = 1000;
ArrayHelper::unique($arr, true) is winner
$max = 10000;
ArrayHelper::unique($arr, true) is winner
$max = 100000;
ArrayHelper::unique($arr) is winner