Skip to content

Instantly share code, notes, and snippets.

@sanasol
Created April 6, 2018 13:56
Show Gist options
  • Save sanasol/9910f13ad881be418eda8f6c645d10b5 to your computer and use it in GitHub Desktop.
Save sanasol/9910f13ad881be418eda8f6c645d10b5 to your computer and use it in GitHub Desktop.
php regexp vs native functions
<?php
$calibration = benchmark(function()
{
});
$benchmark = benchmark(function()
{
$text = "Text oppa post lost kost most dust past";
$char = "p";
if (mb_strlen($char) > 1) {
return -1;
}
return substr_count($text, $char);
});
$benchmark2 = benchmark(function()
{
$text = "Text oppa post lost kost most dust past";
$char = "p";
if (strlen($char) > 1) {
return -1;
}
$re = "/($char)/";
preg_match_all($re, $text, $matches, PREG_SET_ORDER, 0);
return count($matches);
});
echo "Calibration run: " . number_format($calibration) . "/sec\n";
echo "Benchmark substr_count run: " . number_format($benchmark) . "/sec\n";
echo "Benchmark regexp run: " . number_format($benchmark2) . "/sec\n";
echo 'Approximate code substr_count execution time (seconds): ' . number_format((1 / $benchmark) - (1 / $calibration), 10) . PHP_EOL;
echo 'Approximate code regexp execution time (seconds): ' . number_format((1 / $benchmark2) - (1 / $calibration), 10) . PHP_EOL;
function benchmark($x)
{
$start = $t = microtime(true);
$total = $c = $loop = 0;
while (true) {
$x();
$c++;
$now = microtime(true);
if ($now - $t > 1) {
$loop++;
$total += $c;
list($t, $c) = array(
microtime(true),
0
);
}
if ($now - $start > 2) {
return round($total / $loop);
}
}
}
Alexanders-MacBook-Pro:~ sanasol$ php bench.php
Calibration run: 10,551,252/sec
Benchmark substr_count run: 4,608,441/sec
Benchmark regexp run: 1,472,625/sec
Approximate code substr_count execution time (seconds): 0.0000001222
Approximate code regexp execution time (seconds): 0.0000005843
Calibration run: 10,686,848/sec
Benchmark substr_count run: 4,735,970/sec
Benchmark regexp run: 1,478,864/sec
Approximate code substr_count execution time (seconds): 0.0000001176
Approximate code regexp execution time (seconds): 0.0000005826
Calibration run: 10,579,233/sec
Benchmark substr_count run: 4,732,437/sec
Benchmark regexp run: 1,446,469/sec
Approximate code substr_count execution time (seconds): 0.0000001168
Approximate code regexp execution time (seconds): 0.0000005968
Calibration run: 10,673,012/sec
Benchmark substr_count run: 4,644,348/sec
Benchmark regexp run: 1,477,172/sec
Approximate code substr_count execution time (seconds): 0.0000001216
Approximate code regexp execution time (seconds): 0.0000005833
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment