Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

March 29, 2012

the bash way is faster, but only with bash

Some bashisms are syntax sugar at first sight, such as the += concatenation syntax. Usually, they happen to be faster than their more portable counterparts. But only with bash itself.

Take the following script as an example:
#!/bin/sh
# script1-portable.sh
part="$(seq 1 100000)"

for i in $(seq 1 10); do
seq="${part}"
seq="${seq}${part}"
done
$ time bash script1-portable.sh
user 0m20.837s

Now, compare to the following script that uses += :
#!/bin/sh
# script1-bash.sh
part="$(seq 1 100000)"

for i in $(seq 1 10); do
seq="${part}"
seq+="${part}"
done
$ time bash script1-bash.sh
user 0m14.227s

Yes, it's faster. However, when the first script is run with dash:
$ time dash script1-portable.sh
user    0m0.609s

[[ is another example:
#!/bin/sh
# script2-portable.sh
a="$(seq 1 100000)"; b="$(seq 1 100)"

for i in $(seq 1 10); do
[ "$a" = "$b" ]
done
$ time bash script2-portable.sh
user    0m9.148s
And the version using the bashism:
#!/bin/sh
# script2-bash.sh
a="$(seq 1 100000)"; b="$(seq 1 100)"

for i in $(seq 1 10); do
[[ $a = $b ]]
done
$ time bash script2-bash.sh
user    0m4.223s

Then again, the bash way is faster, yet it doesn't compare to dash:
$ time dash script2-portable.sh
user    0m0.588s