note 111530 deleted from function.asort by danbrown

From: Date: Mon, 04 Mar 2013 17:43:22 +0000
Subject: note 111530 deleted from function.asort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193813@lists.php.net to get a copy of this message
Note Submitter: stephen [ at ] brooksie-net [ dot ] co [ dot ] uk ---- In response to nick ([AT]) nickyost ([DOT]) com. With a little testing I found that ksort performs up to 20x faster than usort, up to 52x faster if you also need to convert strings for a case insensitive search. PHP version 5.4 The array tested had 127 entries e.g. : <?php array (size=229) 0 => array (size=10) 'r' => int 66624 'i' => int 5419 'x' => float 1231 'v' => int 448 'j' => float 0 'y' => int 0 'c' => float 0.291244 'cc' => string 'ZW' (length=2) 'l' => float 0.2914 'd' => float 0 ... ?> For int test : orderField = v, orderDesc = 'DESC' For str test : orderField = cc, orderDesc = 'DESC' <?php /** * Sort data set based on given orderField and orderDirection if set. * - In tests this method proved the fastest - * * int : 0.000361 (ms) * str : 0.0004 (ms) * * @param Array $data * @return Array */ private function _keySort($data) { foreach($data as $row) { $tempArray[$row[$this->_orderField]] = $row; } if ($this->_orderDirection == 'DESC') { krsort($tempArray, SORT_NATURAL | SORT_FLAG_CASE ); } else { ksort($tempArray, SORT_NATURAL | SORT_FLAG_CASE); } return $tempArray; } /** * Looks cleaner but performed up to 5 timses slower than method 1 * * ! N.B. Reversed order not tested * * * str : 0.002047 (ms) * int : 0.002067 (ms) * * @param Array $data * @return Array */ public function _uKeySort($data) { foreach($data as $row) { $tempArray[$row[$this->_orderField]] = $row; } uksort($tempArray, "strnatcasecmp"); return ($this->_orderDirection == 'DESC') ? $tempArray : array_reverse($tempArray); } /** * * Considerably slow in comparison. * * results : with strtolower for case insensitivity / case modification commented out * * str : 0.020981 / 0.008773 (ms) * int : 0.011674 / 0.008163 (ms) * * @param Array $data * @return Array */ private function _uSort($data) { usort($data, function ($a,$b) { // convert string values for case insensitivity // if (is_string($a[$this->_orderField])) { // $a[$this->_orderField] = strtolower($a[$this->_orderField]); // $b[$this->_orderField] = strtolower($b[$this->_orderField]); // } return ($this->_orderDirection == 'ASC') ? ($a[$this->_orderField] > $b[$this->_orderField]) : ($a[$this->_orderField] < $b[$this->_orderField]); }); return $data; } ?>

« previous php.notes (#193813) next »