PHP: Fastest way to check if a string is blank

I run an application that requires a very high level of efficiency due to very high volume. I recently did an evaluation of efficiency for this application and performed a benchmark on a number of important aspects of the code. My findings were very interesting.

As you may know, there are a ton of ways to check if a string is empty. These here are not exhaustive, but a few that I chose to test:

  1. !$string
  2. $string == false
  3. empty($string)
  4. strlen($string) == 0
  5. $string == ”

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 string. For what it’s worth, I also checked ‘a’, which had similar results.

PHP 5.2 on Fedora Results

  • !$string = 1.34s
  • $string == ” = 1.53s
  • $string == false = 1.77s
  • empty($string) = 2.91s
  • strlen($string) == 0 = 3.01s

The clear winner is !$string. 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 not surprisingly slow here, because it checks not only if it is a blank string, but also if it equals 0, null, false (and some others). ¬†That also means that depending on your code needs, it may not have a desired effect. Clearly testing strlen() == 0 is a poor choice because there are two operations compared to one for all others (grab string length and then compare it to zero).

PHP 5.3 on Windows 7 Results

It’s worth noting that I ran the same script on my Windows machine¬†(6GB, Quad core, Apache, PHP 5.3) with quite different results. It seems the efficiency of empty() was greatly improved with 5.3. It is actually faster! Obviously 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($string) = 0.63s
  • !$string = 0.67s
  • $string == false = 0.67s
  • $string == ” = 0.68s
  • strlen($string) == 0 = 1.67s

One thought on “PHP: Fastest way to check if a string is blank”

Leave a Reply

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