A couple of years back I wrote about the builtin vs keyword conditional expressions, but I didn’t 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, it’s an external command, there is no point to test, because it’s slow for sure.
With this result, there really isn’t 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 doesn’t do what you think, it’s not arithmetically but lexicographically. In short, it’s for strings, see bash(1), and there is no such this as [[ 1 >= 0 ]].
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.