<?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());
// Run the substr benchmark
// exhaust the gc's threshhold at 10K
$it = 10000;
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']);
// compare the results
$a = array_sum($results['substr']) / $it;
$b = array_sum($results['strpos']) / $it;
printf("substr: %.9fs/iteration @ %d iterations\nstrpos: %.9fs/iteration @ %d iterations\n\n", $a, $it, $b, $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");
}
preferences:
34.75 ms | 402 KiB | 5 Q