I am trying to find out which way to loop in Bash is efficient. The general code is:
#!/bin/bash
t1 () {
tt1=$(date +%s.%N)
}
t2 () {
tt2=$(date +%s.%N)
echo $(echo $tt2 - $tt1 | bc) seconds;
}
TIMES=100000
## brace expansion
t1
for i in {1..100000}
do dummy=1 ; done
t2
## C style
t1
for ((i=1;i<=$TIMES;i++))
do dummy=1 ; done
t2
## seq command
t1
for i in $(seq 1 $TIMES)
do dummy=1 ; done
t2
Surprisingly, C style is neither the fastest one nor the most efficient one in memory usage. Yea, C style doesn’t mean it has the performance as if C code has. Using Brace expansion is the best solution in my test.
However, there is a con in Brace expansion, you can’t program like for i in {1..$TIMES}. In the manual of Bash: Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.
Note: I use Valgrind to get memory usage information with three Bash scripts (extracted from the script above).
References: Brace Expansion, Looping Constructs and Valgrind program.