note 38076 added to function.uksort
| From: | guss at typo dot co dot il | Date: | Sun, 07 Dec 2003 17:18:26 +0000 |
| Subject: | note 38076 added to function.uksort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-61597@lists.php.net to get a copy of this message | ||
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case,
using recursion to compare strings has a huge performance impact while a simple loop would suffice
and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous
example does neither, especially as it does a lot of repetitive things in each iteration, such as
asigning the character order constant, rebuilding it into an array and such
For example, the string comparison could be written as such :
function str_compare($a,$b) {
$order="aAáÁbBcCčČ..."; // longer normally & without that html
entities
$default = strlen($a) - strlen($b);
$minlen = strlen($a) < strlen($b) ? strlen($a) : strlen($b);
for ($i = 0; $i < $minlen; $i++) {
$pos_a=strpos($order,$a[$i]);
$pos_b=strpos($order,$b[$i]);
if ($pos_a != $pos_b)
return $pos_a - $pos_b;
}
return $default;
}
Which is much simpler and faster.
Note that the above function will break for characters that are not listed in $order. it should be
failry trivial to fix it.
----
Manual Page -- http://www.php.net/manual/en/function.uksort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38076
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38076&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38076&report=yes
Search -- http://master.php.net/manage/user-notes.php