note 95875 deleted from function.strpos by cmb
| From: | cmb@php.net | Date: | Sun, 02 Jun 2019 08:05:17 +0000 |
| Subject: | note 95875 deleted from function.strpos by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211171@lists.php.net to get a copy of this message | ||
Note Submitter: daevid at daevid dot com
----
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.