Created
August 6, 2012 00:51
-
-
Save marekkalnik/3268655 to your computer and use it in GitHub Desktop.
Check if string startsWith
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rand_str($length, $switch_chars) | |
{ | |
$valid_chars = 'ABCDEFGHIJKLMNOPQRSabcdefghijklmnopqrs0123456789'; | |
if ($switch_chars) { | |
$valid_chars = 'TUVWXYZtuvwxyz'; | |
} | |
$random_string = ""; | |
$num_valid_chars = strlen($valid_chars); | |
for ($i = 0; $i < $length; $i++) | |
{ | |
$random_pick = mt_rand(1, $num_valid_chars); | |
$random_char = $valid_chars[$random_pick-1]; | |
$random_string .= $random_char; | |
} | |
return $random_string; | |
} | |
function strncmp_strlen($haystack, $needle) | |
{ | |
return !strncmp($haystack, $needle, strlen($needle)); | |
} | |
function substr_strlen($haystack, $needle) | |
{ | |
return substr($haystack, 0, strlen($needle)) === $needle; | |
} | |
function strpos_zero($haystack, $needle) | |
{ | |
return strpos($haystack, $needle) === 0; | |
} | |
function benchmark($func, $haylen, $needlen) | |
{ | |
$haystack = rand_str($haylen, false); | |
$match = substr($haystack, 0, $needlen); | |
$end_match = substr($haystack, strlen($haystack) - $needlen); | |
$no_match = rand_str($needlen, true); | |
$start = microtime(true); | |
for ($i = 0; $i < 500000; $i++) { | |
$func($haystack, $haystack); | |
$func($haystack, $match); | |
$func($haystack, $end_match); | |
$func($haystack, $no_match); | |
} | |
$end = microtime(true); | |
$time = $end - $start; | |
echo $func . " time: " . sprintf('%.4f', $time) . PHP_EOL; | |
} | |
echo "Starting test with 20 letter haystack and 10 letter needle\n"; | |
benchmark('strncmp_strlen', 20, 10); | |
benchmark('substr_strlen', 20, 10); | |
benchmark('strpos_zero', 20, 10); | |
echo "Starting test with 1000 letter haystack and 10 letter needle\n"; | |
benchmark('strncmp_strlen', 1000, 10); | |
benchmark('substr_strlen', 1000, 10); | |
benchmark('strpos_zero', 1000, 10); | |
echo "Starting test with 1000 letter haystack and 800 letter needle\n"; | |
benchmark('strncmp_strlen', 1000, 800); | |
benchmark('substr_strlen', 1000, 800); | |
benchmark('strpos_zero', 1000, 800); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment