Skip to content

Instantly share code, notes, and snippets.

@backbone87
Created February 11, 2015 16:36
Show Gist options
  • Save backbone87/131fca67e40f7100b094 to your computer and use it in GitHub Desktop.
Save backbone87/131fca67e40f7100b094 to your computer and use it in GitHub Desktop.
<?php
$strpos = function($haystack, $needle, $n) {
return function() use($haystack, $needle, $n) {
for($i = 0; $i < $n; $i++) {
if(0 === strpos($haystack, $needle)) {
'ok';
}
}
};
};
$strncmp = function($haystack, $needle, $n) {
$needleLength = strlen($needle);
return function() use($haystack, $needle, $needleLength, $n) {
for($i = 0; $i < $n; $i++) {
if(0 == strncmp($haystack, $needle, $needleLength)) {
'ok';
}
}
};
};
$bench = function($name, $callback, $n = 3) {
$result = array();
echo "Benching $name..." . PHP_EOL;
for($i = 0; $i < $n; $i++) {
$start = microtime(true);
$callback();
$end = microtime(true);
$result[$i] = $end - $start;
echo $i . ': ' . $result[$i] . PHP_EOL;
}
return $result;
};
echo '<pre>';
$haystacks = array(
'short' => '/some/short',
'long' => '/some/short/haystack/oh-wait-this-is-indeed-a-very-long/and-not-so-short/request-string',
);
$needles = array(
'short' => '/some',
'long' => '/some/short',
'short mismatch' => 'not-found',
'long mismatch' => 'this-very-long/needle/is-not-found',
);
$n = 1000000;
foreach($haystacks as $hk => $haystack) {
foreach($needles as $nk => $needle) {
$strposResult = $bench('strpos ' . $hk . ' ' . $nk, $strpos($haystack, $needle, $n));
$strncmpResult = $bench('strncmp ' . $hk . ' ' . $nk, $strncmp($haystack, $needle, $n));
$strposMean = array_sum($strposResult) / count($strposResult);
$strncmpMean = array_sum($strncmpResult) / count($strncmpResult);
echo number_format(100 * ($strncmpMean / $strposMean), 2) . '%' . PHP_EOL . PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment