preg_match vs strpos

Submitted by tomek on Sun, 05/08/2011 - 13:53

f1 is slower than f2 by 108.89% (1.1 times slower)

Full source code as executed.
define('LOOP',1000000);
function f1() {
  $a = 'test string 123';
  for($i=0; $i<LOOP; ++$i) {
    if(preg_match('/123/',$a)) {
    }
  }
}
 
function f2() {
  $a = 'test string 123';
  for($i=0; $i<LOOP; ++$i) {
    if(strpos($a,'123') !== false) {
    }
  }
}
 
$start = microtime(true);
f1();
$stop = microtime(true);
$time1 = $stop - $start;
 
$start = microtime(true);
f2();
$stop = microtime(true);
$time2 = $stop - $start;
 
echo $time1 . "\t";
echo $time2 . "\n";
Test results
comparisontime1time2php_version
86.12%271521614588225.3.5-1ubuntu7.2
77.21%275910815569305.3.3-7
132.35%537931723151735.3.5-1ubuntu7.2
74.97%278700515928065.3.3-7+squeeze1
107.51%390309188090php-5.3.6-phpbrew_compiled
87.34%353989188954php-5.3.7-phpbrew_compiled
111.09%403086190957php-5.3.8-phpbrew_compiled
83.84%373251203031php-5.3.9-phpbrew_compiled
89.88%366446192988php-5.3.10-phpbrew_compiled
123.74%424111189552php-5.3.11-phpbrew_compiled
123.81%423145189062php-5.3.12-phpbrew_compiled
124%423011188844php-5.3.13-phpbrew_compiled
99.43%379379190228php-5.3.14-phpbrew_compiled
70.45%355726208694php-5.3.15-phpbrew_compiled
91.85%399691208337php-5.3.16-phpbrew_compiled
92.85%372187192988php-5.3.17-phpbrew_compiled
105.33%403550196533php-5.3.18-phpbrew_compiled
110.75%409541194329php-5.3.19-phpbrew_compiled
136.87%317334133967php-5.4.0-phpbrew_compiled
109.35%326056155744php-5.4.1-phpbrew_compiled
139.62%350425146240php-5.4.2-phpbrew_compiled
109.16%326526156116php-5.4.3-phpbrew_compiled
162.61%352975134410php-5.4.4-phpbrew_compiled
121.94%333561150290php-5.4.5-phpbrew_compiled
93.59%317795164155php-5.4.6-phpbrew_compiled
111.59%315566149142php-5.4.7-phpbrew_compiled
134.09%314033134148php-5.4.8-phpbrew_compiled
137.49%349365147106php-5.4.9-phpbrew_compiled
50%
updown
50%