Skip to content

Instantly share code, notes, and snippets.

@marcaube
Last active August 29, 2015 14:05
Show Gist options
  • Save marcaube/9099158629f0409e0997 to your computer and use it in GitHub Desktop.
Save marcaube/9099158629f0409e0997 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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