For loops in bash and memory usage
2019-09-04 21:56
There are multiple ways to write a for
-loop in bash. According to one of my favourite resource, nixCraft, there are at least 3 ways.
For loop
for i in {1..10}; do
echo "$i"
done
Seq
for i in $(seq 10); do
echo "$i"
done
Three-expression syntax
for (( i=1; i<=10; i++)); do
echo "$i"
done
The simplest way is probably the first way - it’s easy to read.
However, it has a drawback, when given a large sequence, it takes up a lot of memory:
for i in {1..10000000}; do true; done &
# check top for process memory
I’ve seen it shoot up to 900MB on a Macbook.
for (( i=0; i<=10000000; i++ )); do true; done &
# check top for process memory
The memory usage hovers around 424K.
This is probably because the three-expression syntax only needs to keep a single variable around, whereas the for loop builds up the entire sequence of 10,000,000 numbers.