Created
November 28, 2011 11:53
-
-
Save hpbuniat/1400135 to your computer and use it in GitHub Desktop.
usort is bad
This file contains 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 | |
$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