Well, for a trivially small array, $array === (array) $array
is significantly faster than is_array($array)
. On the order of over 7 times faster. But each call is only on the order of 1.0 x 10 ^ -6
seconds (0.000001 seconds
). So unless you're calling it literally thousands of times, it's not going to be worth it. And if you are calling it thousands of times, I'd suggest you're doing something wrong...
The difference comes when you're dealing with a large array. Since $array === (array) $array
requires a new variable to be copied, it'll likely be SIGNIFICANTLY slower for a large array. For example, on an array with 100 integer elements, is_array($array)
is within a margin of error (< 2%
) of is_array()
with a small array (coming in at 0.0909
seconds for 10,000 iterations). But $array = (array) $array
is extremely slow. For only 100 elements, it's already over twice as slow as is_array()
(coming in at 0.203
seconds). For 1000 elements, in_array
stayed the same, yet the cast comparison increased to 2.0699
seconds...
The reason it's faster for small arrays is that is_array()
has the overhead of being a function call, where the cast operation is a simple language construct... And copying a small variable will typically be cheaper than the function call overhead. But, for larger variables, the difference grows...
It's a tradeoff. Extra memory instead of the overhead of a function call. But eventually, the extra memory will have more overhead than the function call...
I'd suggest going for readability though. I find is_array($array)
to be far more readable than $array === (array) $array
. So you get the best of both worlds.
The script I used for the benchmark:
$elements = 1000;
$iterations = 10000;
$array = array();
for ($i = 0; $i < $elements; $i++) $array[] = $i;
$s = microtime(true);
for ($i = 0; $i < $iterations; $i++) is_array($array);
$e = microtime(true);
echo "in_array completed in " . ($e - $s) ." Seconds\n";
$s = microtime(true);
for ($i = 0; $i < $iterations; $i++) $array === (array) $array;
$e = microtime(true);
echo "Cast completed in " . ($e - $s) ." Seconds\n";
Edit: For the record, these results were with 5.3.2 on Linux...