Skip to content

Instantly share code, notes, and snippets.

@lsmith77
Created December 3, 2012 10:57
Show Gist options
  • Save lsmith77/4194191 to your computer and use it in GitHub Desktop.
Save lsmith77/4194191 to your computer and use it in GitHub Desktop.
matching a list of prefixes, preg_match is of course also more flexible, but it seems like its also going to be faster in many cases
<?php
$iterations = 10000;
$url = '/foo/bar';
$list1 = array('/bar', '/ding', 'dong');
$list2 = array('/foo', '/bar', '/ding', 'dong');
$regexp1 = '/^\/(bar|ding|dong)/';
$regexp2 = '/^\/(bar|foo|ding|dong)/';
function match_strpos($url, $list, $iterations) {
for ($i = 0; $i < $iterations; $i++) {
foreach ($list as $item) {
if (0 === strpos($url, $item)) {
break;
}
}
}
}
function match_regexp($url, $regexp, $iterations) {
for ($i = 0; $i < $iterations; $i++) {
preg_match($regexp, $url);
}
}
$times['init'] = microtime(true);
match_strpos($url, $list1, $iterations);
$times['strpos()/no match '] = microtime(true);
match_regexp($url, $regexp1, $iterations);
$times['preg_match()/no match'] = microtime(true);
match_strpos($url, $list2, $iterations);
$times['strpos()/match '] = microtime(true);
match_regexp($url, $regexp2, $iterations);
$times['preg_match()/match '] = microtime(true);
$previous_time = array_shift($times);
foreach ($times as $key => $time) {
echo("$key: ".($time - $previous_time))."\n";
$previous_time = $time;
}
/*
results without xdebug.so loaded:
strpos()/no match : 0.041649103164673
preg_match()/no match: 0.014512062072754
strpos()/match : 0.016393899917603
preg_match()/match : 0.015846014022827
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment