note 104047 modified in function.strncmp by danbrown

From: Date: Thu, 19 May 2011 14:35:22 +0000
Subject: note 104047 modified in function.strncmp by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179883@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); ?> --was-- 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); http://php.net/manual/en/function.strncmp.php

« previous php.notes (#179883) next »