Skip to content

Instantly share code, notes, and snippets.

@marcaube
Created January 22, 2015 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcaube/4f54660e26294388cf44 to your computer and use it in GitHub Desktop.
Save marcaube/4f54660e26294388cf44 to your computer and use it in GitHub Desktop.
Benchmarking "strlen($string) > 25" vs "isset($string[25])" for speed
<?php
/**
* @param array $functions An associative array of closures to benchmark
* @param int $iterations The number of iterations
*/
function benchmark($functions, $iterations)
{
foreach ($functions as $name => $function) {
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
call_user_func($function);
}
$delta = microtime(true) - $start;
echo "$name: " . $delta . "\n";
}
}
// Fill an array with 10000 strings 1 to 32 chars long
$data = array_fill(1, 10000, substr(md5(rand()), 0, rand(1, 32)));
$functions = array(
'strlen' => function () use ($data) {
foreach ($data as $d) {
$result = (strlen($d) > 25);
}
},
'isset' => function () use ($data) {
foreach ($data as $d) {
$result = isset($d[25]);
}
}
);
echo "Benchmarking \"strlen(\$string) > 25\" vs \"isset(\$string[25])\" ...\n";
benchmark($functions, 10000);
@marcaube
Copy link
Author

Results on an iMac 2.7 GHz Intel Core i5 with 12GB RAM with PHP 5.6.4 (less is better)

strlen: 18.526916980743
isset: 9.9106788635254

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