Geekery

While working on a PHP project, I found myself occasionally switching between using empty() or !strlen() when I was dealing with strings. In PHP, there are often multiple solutions for the same problem and this was one of those cases. I didn’t really have a reason to use one over the other and, as most PHP developers know, you should be careful when using empty() for strings because you can run into this problem:

<?php
    // Here's a string that isn't "empty", it's zero
    $string = '0';
    if (empty($string)) {
        echo 'Oops!';
    }
?>
 
Oops!

Being that I felt capable of being careful with empty(), I wanted to know if there was any speed advantage to using it over strlen(). I wrote a little function and was very surprised by the results:

Checking "if (!strlen($string))" VS "if (empty($string))"
 
unset($string);
Average speed gain using empty() instead of strlen(): 84.62%
 
$string === false;
Average speed gain using empty() instead of strlen(): 57.25%
 
$string = '';
Average speed gain using empty() instead of strlen(): 47.02%

Repeating the test yields similar results every time. Keep in mind, we’re talking fractions of seconds here, but it all adds up. I was expecting there to be a much smaller difference in speed between the two.

Here’s the test I wrote. It’s nothing spectacular and there may be a better way to do it but it gets the job done:

<?php
function test_strlen_vs_empty($string) {
    /* We occasionally have oddities so I wanted to make them observable and count them properly so our avg is accurate */
 
    $oddities = 0;
 
    /* We want to be able to test an unset variable */
    if ($string == 'unset') {
        unset($string);
    }   
 
    /* We'll do 100 tests */
    for ($i = 0; $i < 100; $i++) {
        /* Start our first timer */
        $start_time = microtime(true);
 
        /* We want to check each function 100 times */
        for ($ii = 0; $ii < 100; $ii++) {
            /* Check if the string is empty() */
            if (empty($string)) {
            }   
        }
        /* End our first timer */
        $end_time = microtime(true);
 
        /* Calculate how long it took */
        $time_for_empty = $end_time - $start_time;
 
        /* Start our second timer */
        $start_time = microtime(true);
        for ($ii = 0; $ii < 100; $ii++) {
            /* Check if strlen() returns something equal to false */
            if (!strlen($string)) {
            }   
        }
 
        /* End our second timer */
        $end_time = microtime(true);
 
        /* Calculate how long it took */
        $time_for_strlen = $end_time - $start_time;
 
        /* If strlen() was faster (which doesn't happen often) we want to record it */
        if ($time_for_strlen < $time_for_empty) {
            $oddities++;
        } else {
            /* Otherwise, it's as normal. We want to grab a nice percentage of how much faster empty was than strlen */
            $slowers_total += round(100 - (($time_for_empty / $time_for_strlen) * 100), 2); 
        }   
    }   
    /* Output the results with an average taking into account any oddities that may have occurred */
    echo "\n" . 'Average speed gain using empty() instead of strlen(): ' . round($slowers_total / (100 - $oddities), 2) . '%';
    if ($oddities) {
        echo "\n" . 'Number of times where strlen() was actually faster: ' . $oddities;
    }   
}
 
echo "\n\n" . 'Checking "if (!strlen($string))" VS "if (empty($string))"' . "\n\n";
echo 'unset($string);';
test_strlen_vs_empty('unset');
echo "\n\n" . '$string === false;';
test_strlen_vs_empty(false);
echo "\n\n" . '$string = \'\';';
test_strlen_vs_empty('');
?>

This works by calculating how long it takes to run a check on the string 100 times using each function. It compares the times, and works out how much faster one is over the other in a percentage. This is performed 100 times. At the end, each of the 100 percentages are averaged out to discover how much faster empty() was over strlen(). We check this for three different instances of of empty strings:

  1. When the $string variable is not set
  2. When the $string variable is set to false
  3. When the $string variable is set to a string with no characters (”)

If you look at the code, you’ll see I added handling for “oddities.” Occasionally, strlen() would actually perform faster than empty(). It was random and didn’t happen on every test but it was something that I wanted to observe and properly handle so it’s in there.

So, you may be wondering, why empty() seems to be so much faster. Here is a simple explanation for you. empty() is faster…

“…because empty() is a language construct built into the Zend engine, while strlen is implemented as a standard extension function.

Conclusion: if you are careful enough with empty() you should probably try to use it over strlen() if you’re trying to squeeze all the speed you can out of your application.

If you liked this post, be sure to subscribe to my feed.

  • Avatar

    I don’t believe it is generally cost-effective to streamline code by searching for constructs that give minor performance gains. Especially prickly to me are changes that make unclear your intentions to the next programmer, not that this post is one of those cases. It is worth noting that your test script executes in less than 0.25s on my crappy environment. If I were looking at this are part of a real program, I’d be questioning if I had to loop 100 times way before I questioned empty() vs isset().

    But, rather than pontificating, I’ll get back to the the subject at hand. My preference has always been to use the logical operator ! instead of strlen(), empty(), isset(), or other. Only in the cases where I expect an actual false value, of any type, will I use something else. It stacks up okay in your speed test:

    Checking “if (!strlen($string))” VS “if ( !$string)”

    unset($string);
    Average speed gain using empty() instead of strlen(): 54.34%
    Number of times where strlen() was actually faster: 4

    $string === false;
    Average speed gain using empty() instead of strlen(): 67.63%

    $string = ”;
    Average speed gain using empty() instead of strlen(): 56.1%

  • Every time i come here I am not disappointed, nice post!

    Greetings from Tim. :)

  • Pingback: What is the good practise to see if posted field is not empty? - Page 2()