note 97706 deleted from function.array-multisort by danbrown

From: Date: Tue, 04 May 2010 14:14:20 +0000
Subject: note 97706 deleted from function.array-multisort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168924@lists.php.net to get a copy of this message
Note Submitter: me at aprivateperson dot com ---- 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 */ ?>

« previous php.notes (#168924) next »