I just posted benchmarks for checking for an empty string that I ran when looking to improve the efficiency of an application. Another simple benchmark I ran was for ways to check if an array is empty.
Like strings, there are a ton of ways to check if am array is empty. These here are not exhaustive, but a few that I chose to test:
- !$array
- $array == false
- empty($array)
- count($array) == 0
- $array == array()
I ran each of these checks 1 million times. The machine is 32-bit Fedora, 1.7GB RAM c1.medium Amazon ec2 instance with Apache. PHP is 5.2. I checked with a blank array(). For what it’s worth, I also checked array(‘a’), which had similar results.
PHP 5.2 on Fedora Results
- !$array = 1.35s
- empty($array) = 1.45s
- $array == false = 1.46s
- $array == array() = 1.80s
- count($array) == 0 = 2.34s
Similar to the results from testing strings, the winner is consistently !$array. I’m not a big fan of using this in code because it implies the variable is boolean (the same goes for #2), but it does evaluate to false. empty() is actually not a bad choice here and is considerably faster for checking arrays than strings. Just like strlen() for strings, testing count($array) == 0 is a poor choice because it has to perform two operations.
PHP 5.3 on Windows 7 Results
I also ran the same script on my Windows machine (6GB, Quad core, Apache, PHP 5.3) with quite different results. Again, it would be better to compare 5.2 to 5.3 on the same machine. Perhaps I will if I get some spare time, but I used what I had access to.
- empty($array) = 0.65s
- !$array = 0.65s
- $array == false = 0.68s
- $array == array() = 0.80s
- count($array) == 0 = 1.72s