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.


$array = array();
//$array = range(0, 1000);
for ($i = 0; $i < 1000000; $i++) {


$array = array();
//$array = range(0, 1000);
for ($i = 0; $i < 1000000; $i++) {

The Results

I ran the benchmark about 10 times, and each result confirmed that empty() was roughly 20-30 times faster than count().


% time ./empty.php

real    0m0.122s
user    0m0.094s
sys     0m0.009s


% time ./count.php

real    0m2.630s
user    0m0.118s
sys     0m2.494s

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>