The other day, I began wondering which comparator, test, [, or [[, was fastest? Here are the results:

$ time for i in {1..100000}; do [[ -d . ]];done
real    0m1.256s
user    0m1.018s
sys     0m0.238s
$ time for i in {1..100000}; do [ -d . ];done
real    0m3.407s
user    0m2.704s
sys     0m0.703s
$ time for i in {1..100000}; do test -d .;done

real    0m3.223s
user    0m2.607s
sys     0m0.616s

The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code.

The test and single bracket are the most portable as they exist as separate and external commands. However, if your using any remotely modern version of BASH, the double bracket is supported.

Here is the performance numbers on the external version of test and single bracket:

$ time for i in {1..100000}; do /usr/bin/test -d .;done

real    5m49.324s
user    0m51.771s
sys     4m48.013s
$ time for i in {1..100000}; do /usr/bin/[ -d . ];done

real    5m45.728s
user    0m52.536s
sys     4m46.259s

Wow! This shows the high cost of process creation!

5 Responses to “Which comparator, test, bracket, or double bracket, is fastest?”

  1. Can Bican Says:

    Not really related, but here is another discussion about compatibility of test operations:

    http://www.linuxtopia.org/online_books/linux_development_tools/libtool_autoconf_automake_book/autobook_216.html

  2. eliott Says:

    Interesting.

    It probably isn’t good that you are doing stat calls on the filesystem (even though they are cached) for your test though.

    Doing string comparison may be a better example.

    $ time for i in {1..100000}; do [[ “foo” = “foo” ]]; done
    real 0m1.386s
    user 0m1.368s
    sys 0m0.016s

    $ time for i in {1..100000}; do [ “foo” = “foo” ]; done
    real 0m1.957s
    user 0m1.904s
    sys 0m0.052s

  3. admin Says:

    eliott,

    Good point. I thought about that, but figured since they all can be used that way and it would be cached, it was a valid test.

    However, if the single bracket performs better in string comparisons, that should be noted as well.

  4. admin Says:

    Can Bican,

    Although its not related to the speed, that is a very good article as many admins do not work in as homogeneous environments as myself.

    Thanks for the link!

  5. Six ways to speed up your shell scripts Says:

    […] reading Shell Scripting Recipes, I became more interested in the speed of shell operations. In his book, Chris shows says “Command Substitution Is Slow.” He is […]

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) email the text to me.