Skip to content

Instantly share code, notes, and snippets.

@live627
Forked from joshuaadickerson/instr.php
Last active July 9, 2023 08:51
Show Gist options
  • Save live627/40e6a93ebdb13d758420569dfd4e4f9b to your computer and use it in GitHub Desktop.
Save live627/40e6a93ebdb13d758420569dfd4e4f9b to your computer and use it in GitHub Desktop.
An insitu (no copy) string comparison comparable to substr_compare()
<?php
function instr(string $string, string $substr, int $offset = 0, int $length = null): bool
{
for ($pos = $offset, $substr_pos = 0; $pos !== $length; $pos++, $substr_pos++)
{
if (isset($substr[$substr_pos]))
{
if (isset($string[$pos]))
{
if ($string[$pos] !== $substr[$substr_pos])
return false;
}
else
return false;
}
else
{
if ($length === null || $length + 1 === $substr_pos)
return true;
if (isset($string[$pos]))
return false;
}
}
return true;
}
function test($haystack, $needle) {
$repetitions = 0;
$start = microtime(true);
do {
strpos($haystack, $needle);
$repetitions += 1;
} while (microtime(true) - $start < 5);
$rate = round($repetitions / (microtime(true) - $start));
$rate = str_pad($rate, 8, ' ', STR_PAD_LEFT);
echo "$rate / second\n";
$repetitions = 0;
$start = microtime(true);
do {
instr($haystack, $needle);
$repetitions += 1;
} while (microtime(true) - $start < 5);
$rate = round($repetitions / (microtime(true) - $start));
$rate = str_pad($rate, 8, ' ', STR_PAD_LEFT);
echo "$rate / second\n\n";
}
// Worst case
test(str_repeat('A', 1e+7) . 'BB', 'BB');
test(str_repeat('aA', 1e+6) . 'aB', 'aB');
test(str_repeat('A', 1e+1) . 'BB', 'BB');
test(str_repeat('aA', 1e+1) . 'aB', 'aB');
// Best case
test(str_repeat('a', 1e+7), 'aa');
test(str_repeat('aa', 1e+6), 'aa');
test(str_repeat('a', 1e+1), 'aa');
test(str_repeat('aA', 1e+1), 'aa');
$string = 'abcdefghijklmnopqrstuvwxyz';
$substr = 'def';
$offset = 3;
$length = 0;
var_dump(instr($string, $substr, $offset, $length));
@live627
Copy link
Author

live627 commented Jul 9, 2023

php -v
PHP 8.1.1 (cli) (built: Dec 15 2021 10:31:43) (ZTS Visual C++ 2019 x64)

11th Gen Intel(R) Core(TM) i7-11700F @ 2.50GHz


    3847 / second
 9553267 / second

     297 / second
 7184814 / second

14038493 / second
 9540673 / second

10923208 / second
 7027445 / second

14676242 / second
 6136964 / second

14933345 / second
 6169539 / second

14700096 / second
 6136005 / second

11542197 / second
 7023714 / second

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment