Created
January 22, 2015 21:34
-
-
Save marcaube/4f54660e26294388cf44 to your computer and use it in GitHub Desktop.
Benchmarking "strlen($string) > 25" vs "isset($string[25])" for speed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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