Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Last active December 12, 2015 06:49
Show Gist options
  • Save ajcrites/4732454 to your computer and use it in GitHub Desktop.
Save ajcrites/4732454 to your computer and use it in GitHub Desktop.
Attempts to check how efficient multiple strpos checks are relative to the same number of PCRE function checks. String length has a significant impact on finding a string with a regular expression pattern. You can specify how long the string is via an argument to the script. `strpos` is always faster; period. It takes the same amount of time eve…
$ php strposvsstriposvspregbench.php 1
0.40396499633789
0.58028793334961
0.93481206893921
0.91582679748535

$ php strposvsstriposvspregbench.php 100
0.42313885688782
0.50706505775452
4.8115060329437
4.7086510658264
<?php
$char = str_repeat(' ', $argv[1]) . '_';
$time = microtime(true);
for ($_ = 0; $_ < 1000000; $_++) {
strpos('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_', $char);
}
echo microtime(true) - $time . "\n";
$time = microtime(true);
for ($_ = 0; $_ < 1000000; $_++) {
stripos('abcdefghijklmnopqrstuvwxyz1234567890-_', $char);
}
echo microtime(true) - $time . "\n";
$time = microtime(true);
for ($_ = 0; $_ < 1000000; $_++) {
preg_match('/[a-zA-Z0-9-_]/', $char);
}
echo microtime(true) - $time . "\n";
$time = microtime(true);
for ($_ = 0; $_ < 1000000; $_++) {
preg_match('/[a-z0-9-_]/i', $char);
}
echo microtime(true) - $time . "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment