Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmarking "(array) $var === $var" vs "is_array($var)" 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";
}
}
$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);
@marcaube

This comment has been minimized.

Copy link
Owner Author

@marcaube marcaube commented Aug 19, 2014

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

casting: 6.4870979785919
is_array: 0.010051012039185

@marcaube

This comment has been minimized.

Copy link
Owner Author

@marcaube marcaube commented Aug 19, 2014

Using the same benchmark function, comparing count($array) == 0 vs empty($array) (less is better)

count(): 4.2716100215912
empty(): 3.3020689487457

<?php

// ...

echo "\nBenchmarking \"count(\$var) == 0\" vs \"empty(\$var)\" ...\n";

$data = range(1, 1000000);

benchmark(array(
    'count()' => function () use ($data) {
        $result = count($data) == 0;
    },
    'empty()' => function () use ($data) {
        $result = empty($data);
    }
), 10000000);
@marcaube

This comment has been minimized.

Copy link
Owner Author

@marcaube marcaube commented Aug 19, 2014

in_array_keys($key, $array) vs $array[$key] (less is better)

in_array_keys(): 4.8499279022217
key check: 3.8257780075073

<?php

// ...

echo "\nBenchmarking \"array_key_exists(\$key, \$array)\" vs \"\$array[\$key]\" ...\n";

$data = array_fill_keys(range(1, 1000), uniqid());

benchmark(array(
    'in_array_keys()' => function () use ($data) {
        $result = array_key_exists(50, $data) ? : null;
    },
    'key check' => function () use ($data) {
        $result = $data[50] ? : null;
    }
), 10000000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment