- strpos: documentation ( source)
- function_exists: documentation ( source)
- hrtime: documentation ( source)
- str_starts_with: documentation ( source)
<?php
if ( ! function_exists( 'str_starts_with' ) ) {
function str_starts_with( $haystack, $needle ) {
if ( '' === $needle ) {
return true;
}
return 0 === strpos( $haystack, $needle );
}
}
$string = 'abcdefghijklmnopqrstuvwxyz';
$start = hrtime(true);
for ( $i = 0; $i < 1000000; $i++ ) {
$result1 = str_starts_with( $string, 'abc' );
$result2 = str_starts_with( $string, 'abd' );
}
$end = hrtime(true);
$str_starts_with_time = $end - $start;
$start = hrtime(true);
for ( $i = 0; $i < 1000000; $i++ ) {
$result1 = 0 === strpos( $string, 'abc' );
$result2 = 0 === strpos( $string, 'abd' );
}
$end = hrtime(true);
$strpos_time = $end - $start;
echo 'str_starts_with: ' . $str_starts_with_time . PHP_EOL;
echo 'strpos: ' . $strpos_time . PHP_EOL;
// echo which function is faster
if ( $str_starts_with_time < $strpos_time ) {
echo 'str_starts_with is faster' . PHP_EOL;
} else {
echo 'strpos is faster' . PHP_EOL;
}