note 97707 added to function.usort
| From: | me at aprivateperson dot com | Date: | Tue, 04 May 2010 12:48:04 +0000 |
| Subject: | note 97707 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168915@lists.php.net to get a copy of this message | ||
When sorting multi-dimensional arrays, array_multisort() is roughly twice as fast as an equivalent
usort(). This speed advantage seems to grow with the size of the array being sorted.
<?
$numtimes=100000;
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
function cmp($a, $b) {
if ($a['edition'] == $b['edition']) {
if ($a['volume']==$b['volume']) { return 0; }
return (($a['volume']<$b['volume'])?-1:1);
}
return ($a['edition'] < $b['edition']) ? -1 : 1;
}
$start=microtime(true);
for ($z=0;$z<$numtimes;$z++) {
$t=$data;
usort($t, "cmp");
}
$start1=microtime(true);
for ($z=0;$z<$numtimes;$z++) {
$t=$data;
foreach ($t as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
array_multisort($t, $edition, SORT_ASC, $volume, SORT_ASC);
}
$start2=microtime(true);
echo "<table><tr><td>$start</td></tr>",
"<tr><td>$start1</td><td>",($start1-$start),"</td></tr>",
"<tr><td>$start2</td><td>",($start2-$start1),"</td></tr>",
"</table>";
/*
output:
1272974926.88
1272974928.62 1.74083399773
1272974929.57 0.9506919384
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 74.70.104.254
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/97707
Del: integrated -- https://master.php.net/note/delete/97707/integrated
Del: useless -- https://master.php.net/note/delete/97707/useless
Del: bad code -- https://master.php.net/note/delete/97707/bad+code
Del: spam -- https://master.php.net/note/delete/97707/spam
Del: non-english -- https://master.php.net/note/delete/97707/non-english
Del: in docs -- https://master.php.net/note/delete/97707/in+docs
Del: other reasons-- https://master.php.net/note/delete/97707
Reject -- https://master.php.net/note/reject/97707
Search -- https://master.php.net/manage/user-notes.php