Skip to content

Instantly share code, notes, and snippets.

@lucasnetau
Created May 3, 2025 04:35
Show Gist options
  • Save lucasnetau/8f134b59e1dc25f52744cb9fb6799685 to your computer and use it in GitHub Desktop.
Save lucasnetau/8f134b59e1dc25f52744cb9fb6799685 to your computer and use it in GitHub Desktop.
<?php
$results = [];
$short = random_bytes(128);
$short_match = substr($short, 0, 8);
$short_nomatch_head = str_repeat('a', 8);
$short_nomatch_tail = substr($short, 0, 7) . str_repeat('a', 4);
$medium = random_bytes(1024);
$medium_match = substr($medium, 0, 128);
$medium_nomatch_head = str_repeat('a', 128);
$medium_nomatch_tail = substr($short, 0, 124) . str_repeat('a', 4);
$long = random_bytes(4096);
$long_match = substr($long, 0, 512);
$long_nomatch_head = str_repeat('a', 512);
$long_nomatch_tail = substr($short, 0, 508) . str_repeat('a', 4);
$xlong = random_bytes(8096);
$xlong_match = substr($xlong, 0, 1024);
$xlong_nomatch_head = str_repeat('a', 1024);
$xlong_nomatch_tail = substr($short, 0, 1020) . str_repeat('a', 4);
$iterations = 10000000;
foreach (['short','medium','long','xlong'] as $key) {
foreach (['match', 'nomatch_head', 'nomatch_tail'] as $key2) {
$test = $key . "_" . $key2;
$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
$res = str_starts_with($key, $$test);
}
$results["str_starts_with_$test"] = (hrtime(true) - $start);
$len = strlen($$test);
$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
$res = strncmp($key, $$test, $len);
}
$results["strncmp_$test"] = (hrtime(true) - $start);
}
}
asort($results);
foreach($results as $func => $time) {
echo "$func: " . number_format($time/$iterations, 0) . " ns per call\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment