<?php
function starts_with_strpos($haystack, $needle) {
return strpos($haystack, $needle) === 0;
}
function starts_with_substr($haystack, $needle) {
return substr($haystack, 0, strlen($needle)) === $needle;
}
// setup the haystack and needle
$haystack = "Hello PHP";
$needle = "Hello";
// initialize the results array
$results = array('substr' => array(), 'strpos' => array(), 'strpos_without_function' => array());
// exhaust the gc's threshhold at 10K
$it = 10000;
// Run the substr benchmark
for($i = 0; $i < $it; $i++) {
$t = microtime(true);
starts_with_substr($haystack, $needle);
$results['substr'][] = microtime(true) - $t;
}
// discard the first and last results as opline biased
array_pop($results['substr']);
array_shift($results['substr']);
// Run the strpos benchmark
for($i = 0; $i < $it; $i++) {
$t = microtime(true);
starts_with_strpos($haystack, $needle);
$results['strpos'][] = microtime(true) - $t;
}
// discard the first and last results as opline biased
array_pop($results['strpos']);
array_shift($results['strpos']);
// Run the strpos without a wrapper function benchmark
for($i = 0; $i < $it; $i++) {
$t = microtime(true);
strpos($haystack, $needle) === 0;
$results['strpos_without_function'][] = microtime(true) - $t;
}
// discard the first and last results as opline biased
array_pop($results['strpos_without_function']);
array_shift($results['strpos_without_function']);
// compare the results
$a = array_sum($results['substr']) / $it;
$b = array_sum($results['strpos']) / $it;
$c = array_sum($results['strpos_without_function']) / $it;
printf("substr: %.9fs/iteration @ %d iterations\nstrpos: %.9fs/iteration @ %d iterations\nstrpos (without wrapper): %.9fs/iteration @ %d iterations\n\n", $a, $it, $b, $it, $c, $it);
// determine which is faster (substr or strpos)
if ($a > $b) { // substr is slower
printf("strpos is %d%% faster than substr\n", $b / $a * 100);
} elseif ($b > $a) { // strpos is slower
printf("substr is %d%% faster than strpos\n", $a / $b * 100);
} else { // they're the same
printf("strpos and substr are the same\n");
}
// determine which is faster (strpos with a wrapper or without)
if ($b > $c) { // strpos wrapper is slower
printf("strpos without a wrapper function is %d%% faster than strpos with a wrapper function\n", $c / $b * 100);
} elseif ($c > $b) { // strpos wrapper is faster
printf("strpos with a wrapper function is %d%% faster than strpos without a wrapper fucntion\n", $b / $c * 100);
} else { // they're the same
printf("strpos and substr are the same\n");
}