note 95874 added to function.strpos
| From: | daevid at daevid dot com | Date: | Tue, 26 Jan 2010 22:44:29 +0000 |
| Subject: | note 95874 added to function.strpos | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-165344@lists.php.net to get a copy of this message | ||
Dan Brown and I had a discussion on the PHP list about the speed difference between the popular
three string searching techniques. He wrote a simple timing test, and I adapted it further. The end
result is that all three are very close and not even noticeable for sets < 1M. Although,
technically strpos() is about twice as fast (as the docs allude to above). Here it is for your own
amusement and testing purposes.
<?php
for ($i = 0; $i < 1000000; $i++ )
$o[] =
sprintf('%04d-%02d-%02d',rand(0000,9999),rand(00,99),rand(00,99));
#print_r($o);
echo "array of ".number_format($i)."\n";
###################################################################
$now = microtime(true);
for($i=0;$i<count($o);$i++) {
if(preg_match('/^[0]{4,}\-/U',$o[$i])) {
//echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
}
}
$rank['preg_match'] = (microtime(true) - $now);
###################################################################
$later = microtime(true);
for($i=0;$i<count($o);$i++) {
if(substr($o[$i],0,4) == "0000") {
//echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
}
}
$rank['substr'] = (microtime(true) - $later);
###################################################################
$after = microtime(true);
for($i=0;$i<count($o);$i++) {
if(strpos($o[$i], '0000') === 0) {
//echo "Offset #".$i." matches: ".$o[$i].PHP_EOL;
}
}
$rank['strpos'] = (microtime(true) - $after);
###################################################################
asort($rank);
print_r($rank);
?>
array of 10,000
Array
(
[strpos] => 0.00766682624817
[substr] => 0.0116670131683
[preg_match] => 0.0124950408936
)
array of 100,000
Array
(
[strpos] => 0.0817799568176
[substr] => 0.120522975922
[preg_match] => 0.125612974167
)
array of 1,000,000
Array
(
[strpos] => 0.805890083313
[substr] => 1.19799995422
[preg_match] => 1.25615906715
)
I ran out of memory with more than 1M array elements.
----
Server IP: 208.69.120.55
Probable Submitter: 206.169.197.253
----
Manual Page -- http://www.php.net/manual/en/function.strpos.php
Edit -- https://master.php.net/note/edit/95874
Del: integrated -- https://master.php.net/note/delete/95874/integrated
Del: useless -- https://master.php.net/note/delete/95874/useless
Del: bad code -- https://master.php.net/note/delete/95874/bad+code
Del: spam -- https://master.php.net/note/delete/95874/spam
Del: non-english -- https://master.php.net/note/delete/95874/non-english
Del: in docs -- https://master.php.net/note/delete/95874/in+docs
Del: other reasons-- https://master.php.net/note/delete/95874
Reject -- https://master.php.net/note/reject/95874
Search -- https://master.php.net/manage/user-notes.php