note 21804 added to ref.strings
| From: | R dot J dot Vrijhof at bigfoot dot com | Date: | Tue, 28 May 2002 02:47:51 +0000 |
| Subject: | note 21804 added to ref.strings | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-31082@lists.php.net to get a copy of this message | ||
The author from the getNth() function is right in his assumption that it is faster than the nth()
function, which does the same, but with more code (and a LOT less gracefully IMHO).
I have tested it out with a little profiling script and it looks like getNth() is about twice as
fast than nth().
If you want to test it out yourself, here is the code of the profiling script:
<?php
function getNth ($n) {
$qn = (int) (($n%100) / 10);
$rn = $n % 10;
$suffix = "th";
if ($qn != 1) {
switch ($rn) {
case 1: $suffix = "st"; break;
case 2: $suffix = "nd"; break;
case 3: $suffix = "rd"; break;
}
}
return $n . $suffix;
}
function nth($in) {
if (! is_long($in))
return(-1);
switch ($in) {
case 0 : return("0th");
case 1 : return("1st");
case 2 : return("2nd");
case 3 : return("3rd");
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
case 9 :
case 10 :
case 11 :
case 12 :
case 13 :
case 14 :
case 15 :
case 16 :
case 17 :
case 18 :
case 19 : return($in."th");
}
switch (substr($in, -1, 1)) {
case 0 : return($in."th");
case 1 : return($in."st");
case 2 : return($in."nd");
case 3 : return($in."rd");
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
case 9 : return($in."th");
default : return(0);
}
}
function mtime() {
list($sec, $msec) = explode(" ", microtime());
return (float) $sec + (float) $msec;
}
$iterations = 50000;
$start_nth = mtime();
for ($a = 0; $a < $iterations; $a++) {
nth($a);
}
$end_nth = mtime();
$delta_nth = $end_nth - $start_nth;
printf("<p>nth() took %1.2f seconds to complete $iterations
iterations.</p>\n", $delta_nth);
$start_getNth = mtime();
for ($a = 0; $a < $iterations; $a++) {
getNth($a);
}
$end_getNth = mtime();
$delta_getNth = $end_getNth - $start_getNth;
printf("<p>getNth() took %1.2f seconds to complete $iterations
iterations.</p>\n", $delta_getNth);
if ($delta_nth > $delta_getNth) {
printf("<p>getNth() is about %1.1f times faster than nth().</p>\n",
$delta_nth / $delta_getNth);
} else {
printf("<p>nth() is about %1.1f times faster than getNth().</p>\n",
$delta_getNth / $delta_nth);
}
?>
P.S.: sorry for the broken lines (all lines that have "printf" in them) in the above
script...
--
http://www.php.net/manual/en/ref.strings.php
http://master.php.net/manage/user-notes.php?action=edit+21804
http://master.php.net/manage/user-notes.php?action=delete+21804
http://master.php.net/manage/user-notes.php?action=reject+21804