I need to run a check on multiple variables, some of which will be urls and others will only contain no more than 5 or 6 characters, none of which will ever be "http".
Which of the two methods below gives the best performance in terms of speed and processor load.
$str = 'http://somereallylongwebaddress.com';
if (substr( $str, 0, 4 ) === "http") {
// true
}
if (strlen( $str >= 7 )) {
// true
}
EDIT For anybody else that is interested I found this great page which runs live comparisons of various different functions. It doesn't address my particular one but very informative all the same.
You can run following code in any of online php editors below using different inputs and observe the speed performance.
http://www.writephponline.com/
https://www.tutorialspoint.com/php_webview_online.php
<?php
$before = microtime(true);
$str = "http";
if (substr( $str, 0, 4 ) === "http") {
// true
}
echo "strlen performance ";
echo "Time: " . number_format(( microtime(true) - $before), 8) . " Seconds\n";
echo "\r\n";
$before = microtime(true);
if (strlen($str >= 4)) {
// true
}
echo "substr performance ";
echo "Time: " . number_format(( microtime(true) - $before), 8) . " Seconds\n";
echo "\r\n";
?>
Based on multiple results from above code snippet, substr is showing better performance in terms of speed. In terms of processor load, assembly code for each function needs to compare.