note 94512 deleted from function.microtime by danbrown
| From: | danbrown@php.net | Date: | Tue, 10 Nov 2009 15:40:55 +0000 |
| Subject: | note 94512 deleted from function.microtime by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162712@lists.php.net to get a copy of this message | ||
Note Submitter: shavais at gmail dot com
----
<?php
function endswith1($s, $e) {
return ( substr($s, strlen($s) - strlen($e)) == $e );
}
function endswith2($s, $e) {
$e = preg_quote($e);
return preg_match("/($e)$/", $s);
}
function control($s, $e) {return null;}
function timereps($func, $reps) {
$s = "path/to/file/somefile.csv";
$e = ".csv";
$t1 = microtime(true);
for ($i = 0; $i< $reps; $i++) {
$dmy = $func($s, $e);
}
$t2 = microtime(true);
return $t2 - $t1;
}
print "substr time: ".($e1 = timereps('endswith1', 370000))."\n";
print "preg_match time: ".($e2 = timereps('endswith2', 370000))."\n";
print "control time: ".($ct = timereps('control', 370000))."\n";
print "preg_match vs substr: ".(100.0 * (($e2-$ct) / ($e1-$ct)))."\n";
?>
When I run the above, I get widely varying results, but most of the results show the substr/strlen
version outperforming the preg_match version by between about 30 to 40% if separated out into a
dedicated function call, or 70 to 80% if done in-line (if I take out the time it takes to make a
function call):
substr time: 0.66379904747009
preg_match time: 0.91860914230347
control time: 0.32123684883118
preg_match vs substr: 174.38359978007
Both, however, on my (relatively high powered) office desktop, can fairly reliably be done 370,000
times or more in one second, so, the slower performance of preg_match may be a non-issue in the vast
majority of cases.