Skip to content

Instantly share code, notes, and snippets.

@datibbaw
Created March 1, 2013 02:37
Show Gist options
  • Save datibbaw/5062085 to your computer and use it in GitHub Desktop.
Save datibbaw/5062085 to your computer and use it in GitHub Desktop.
php startsWith() comparison
<?php
function startswith1($haystack, $needle)
{
return substr($haystack, 0, strlen($needle)) === $needle;
}
function startswith2($haystack, $needle)
{
return preg_match('/^'.preg_quote($needle,'/').'/', $haystack) > 0;
}
function startswith3($haystack, $needle)
{
return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function startswith4($haystack, $needle)
{
return strpos($haystack, $needle) === 0;
}
function startswith5($haystack, $needle)
{
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
function testall($haystack, $needle, $n, $desc)
{
echo "Test case: $desc ($n iterations)\n";
$results = array();
$start = microtime(true);
for ($i = 0; $i != $n; ++$i) {
startswith1($haystack, $needle);
}
$results['startswith1'] = microtime(true) - $start;
$start = microtime(true);
for ($i = 0; $i != $n; ++$i) {
startswith2($haystack, $needle);
}
$results['startswith2'] = microtime(true) - $start;
$start = microtime(true);
for ($i = 0; $i != $n; ++$i) {
startswith3($haystack, $needle);
}
$results['startswith3'] = microtime(true) - $start;
$start = microtime(true);
for ($i = 0; $i != $n; ++$i) {
startswith4($haystack, $needle);
}
$results['startswith4'] = microtime(true) - $start;
$start = microtime(true);
for ($i = 0; $i != $n; ++$i) {
startswith5($haystack, $needle);
}
$results['startswith5'] = microtime(true) - $start;
showresults($results);
}
function showresults(array $results)
{
$min = PHP_INT_MAX;
$minkey = -1;
foreach ($results as $key => $time) {
if ($time < $min) {
$min = $time;
$minkey = $key;
}
}
foreach ($results as $key => $time) {
echo sprintf("%-20s%-10.5f %s\n", $key, $time, $key === $minkey ? '(fastest)' : '-' . number_format(100 * ($time - $min) / $min, 2) . '%');
}
}
$c_twokay = str_repeat('c', 2048);
$c_128 = str_repeat('c', 128);
$d_128 = str_repeat('d', 128);
$cd_128 = str_repeat('c', 64) . str_repeat('d', 64);
testall($c_twokay, 'd', 200000, 'Single char needle, 2k haystack, no match');
testall($c_twokay, 'c', 200000, 'Single char needle, 2k haystack, match');
testall($c_twokay, $d_128, 200000, '128 byte needle, 2k haystack, no match');
testall($c_twokay, $c_128, 200000, '128 byte needle, 2k haystack, match');
testall($c_twokay, $cd_128, 200000, '64+64 byte needle, 2k haystack, no match');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment