Last active
August 29, 2015 14:05
-
-
Save marcaube/9099158629f0409e0997 to your computer and use it in GitHub Desktop.
Benchmarking "(array) $var === $var" vs "is_array($var)" 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"; | |
} | |
} | |
$data = array( | |
'string', // Not an array | |
array(1, 2, 3), // Small array | |
array_fill(1, 10000, uniqid()) // Large-ish array | |
); | |
$functions = array( | |
'casting' => function () use ($data) { | |
foreach ($data as $d) { | |
$result = (array) $d === $d; | |
} | |
}, | |
'is_array' => function () use ($data) { | |
foreach ($data as $d) { | |
$result = is_array($d); | |
} | |
} | |
); | |
echo "Benchmarking \"(array) \$var === \$var\" vs \"is_array(\$var)\" ...\n"; | |
benchmark($functions, 10000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in_array_keys($key, $array)
vs$array[$key]
(less is better)in_array_keys(): 4.8499279022217
key check: 3.8257780075073