As of 2016-02-26, there will be no more posts for this blog. s/blog/pba/
Showing posts with label comparison. Show all posts

A couple of years back I wrote about the builtin vs keyword conditional expressions, but I didnt think about another conditional use with arithmetic, that is with tests like [ $a -gt $b] or [[ $a -ne 0 ]].

Use similar code to benchmark 1 > 0 as shown below, not the real code, but you get the idea:

time for ((i = 0; i < 10000; i++)); do <test> 1 >/-gt 0 ; done

The result is:

<test> with time % slower
[ 6.647s 47.9%
[[ 4.692s 04.4%
(( 4.493s fastest
test (builtin) 6.538s 45.5%

(( is just marginally faster than [[ by my definition. Of course, they both are faster than builtin [ and test, as for /usr/bin/test, its an external command, there is no point to test, because its slow for sure.

With this result, there really isnt much difference between two, however, 1 > 0 is more readable than 1 -gt 0, literally and mathematically.

Note

Yes, [[ 1 > 0 ]] is a valid syntax, but it doesnt do what you think, its not arithmetically but lexicographically. In short, its for strings, see bash(1), and there is no such this as [[ 1 >= 0 ]].

Even since I started writing Bash script, I always use [[ for if conditional statement, the double square brackets, never the single one version unless compatibility has to be taken into account. Why did I choose it? Its because I read [[ is faster. Ive never tried to confirm it by myself, although I do know that [ is a type of shell builtin command and [[ is type of shell keyword, and [ is equivalent to test, which is also a builtin command in Bash for very long time.1

Note

[ and [[ can also be used for arithmetic comparison, such as the use of -gt operator, see another test with Arithmetic Evaluation, ((. This post only focuses on the strings.

From time to time, I often see people still using [ even in the script with a few Bash-only syntaxes or features. They are clearly not writing with compatibility as a requirement. If I have a chance, then I would probably advise the coder to change to [[. I had done so a few times in the past.

However, I never see the numbers, so I used the following to test:

time for ((i = 0; i < 10000; i++)); do <test> -z '' ; done

The result is:

<test> with time % slower
[ 00.149s 00,063.7%
[[ 00.091s fastest
test (builtin) 00.150s 00,064.8%
/usr/bin/test 13.798s 15,063.6%

[ and test possibly are synonyms since they are pretty close.

As you can see [[ definitely is the winner, and /usr/bin/test external command is the slowest. The problem with /usr/bin/test isnt that is inefficient, but external command is costly.

If you are new to Bash, just use [[.

[1]If you dont know the differences between keyword, builtin command, and external command, google them.