Skip to content

Instantly share code, notes, and snippets.

@miyukki
Created July 31, 2012 09:03
Show Gist options
  • Save miyukki/3215296 to your computer and use it in GitHub Desktop.
Save miyukki/3215296 to your computer and use it in GitHub Desktop.
substr_count vs preg_match_all
<?php
$needle = '';
$str = 'hello, world!';
$search_str = 'hello';
$count = 100;
for($i = 0; $i < $count; $i++) {
$needle .= $str;
}
// substr_count
$start = microtime(TRUE);
$out = substr_count($needle, $search_str);
$end = microtime(TRUE);
echo 'out: '.$out.PHP_EOL;
echo 'substr_count: '.($end-$start).PHP_EOL;
// preg_match_all
$start = microtime(TRUE);
$out = preg_match_all('/'.$search_str.'/', $needle, $matches);
$end = microtime(TRUE);
echo 'out: '.$out.PHP_EOL;
echo 'preg_match_all: '.($end-$start).PHP_EOL;
//out: 100
//substr_count: 7.1525573730469E-6
//out: 100
//preg_match_all: 8.4877014160156E-5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment