Skip to content

Instantly share code, notes, and snippets.

@hpbuniat
Created November 28, 2011 11:53
Show Gist options
  • Save hpbuniat/1400135 to your computer and use it in GitHub Desktop.
Save hpbuniat/1400135 to your computer and use it in GitHub Desktop.
usort is bad
<?php
$aOpts = getopt('i:');
if (empty($aOpts['i']) === true) {
$aOpts = array(
'i' => 10000
);
}
$aValues = range(0, $aOpts['i'], 1);
shuffle($aValues);
$aTest = array();
foreach ($aValues as $iValue) {
$aTest[md5($iValue)]['price'] = $iValue;
}
$aClone = $aTest;
$fStart = microtime(true);
usort($aClone, '_usort');
$fUsort = (microtime(true) - $fStart);
print_r('usort: ' . $fUsort . PHP_EOL);
$aClone = $aTest;
$fStart = microtime(true);
_testSort($aClone);
$fTestSort = (microtime(true) - $fStart);
print_r('_testSort: ' . $fTestSort . PHP_EOL);
print_r('Diff: ' . round($fUsort / $fTestSort, 2) . PHP_EOL);
function _usort($a, $b) {
return $a['price'] > $b['price'] ? 1 : (($a['price'] == $b['price']) ? 0 : -1);
}
function _testSort(&$aSort) {
$aReturn = $aKeyValue = array();
foreach ($aSort as $mKey => $aItem) {
$aKeyValue[$mKey] = $aItem['price'];
}
asort($aKeyValue);
$aKeys = array_keys($aKeyValue);
foreach ($aKeys as $mKey) {
$aReturn[] = $aSort[$mKey];
}
$aSort = $aReturn;
unset($aKeys, $aKeyValue, $aReturn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment