Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@marcaube marcaube commented Jan 22, 2015

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