note 104047 added to function.strncmp
| From: | bobvin at pillars dot net | Date: | Thu, 19 May 2011 14:25:15 +0000 |
| Subject: | note 104047 added to function.strncmp | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179882@lists.php.net to get a copy of this message | ||
For checking matches at the beginning of a short string, strpos() is about 15% faster than
strncmp().
Here's a benchmark program to prove it:
<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
$times['strncmp'][$needle] = -microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$result = strncmp($haystack, $needle, 3) === 0;
}
$times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
$times['strpos'][$needle] = -microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$result = strpos($haystack, $needle) === 0;
}
$times['strpos'][$needle] += microtime(true);
}
var_export($times);
----
Server IP: 69.147.83.197
Probable Submitter: 68.228.136.120
----
Manual Page -- http://www.php.net/manual/en/function.strncmp.php
Edit -- https://master.php.net/note/edit/104047
Del: integrated -- https://master.php.net/note/delete/104047/integrated
Del: useless -- https://master.php.net/note/delete/104047/useless
Del: bad code -- https://master.php.net/note/delete/104047/bad+code
Del: spam -- https://master.php.net/note/delete/104047/spam
Del: non-english -- https://master.php.net/note/delete/104047/non-english
Del: in docs -- https://master.php.net/note/delete/104047/in+docs
Del: other reasons-- https://master.php.net/note/delete/104047
Reject -- https://master.php.net/note/reject/104047
Search -- https://master.php.net/manage/user-notes.php