PHP Benchmark: count() vs. empty()

In my experience, PHP is not a very “fast” language. Opcode and memory caching are important to many large projects, but they will not make up for poor decisions made when writing code. In recent years, we’ve seen the PHP team integrate opcode cache into PHP 5.5, and Facebook investing in HipHop. These are welcome improvements, but we need to be smart about what functions and language constructs we use.

Given an empty array, empty() will return false, and count() will return zero. Given an array with one or more values, empty() will return true, and count() will return the number of values. Either method will produce an effective result in a conditional checking for a boolean value (==), but how do they perform? First, let’s look at the code used for the benchmark.

The Code

The code is simple. In both files, we executed each function/construct one million times and measured the results with Linux’s time command. In addition to testing with an empty array, I also benchmarked count() and empty() on an array with 1,000 values. There was no measurable variance between the performance of an empty array and an array with 1,000 values.