Bash array iteration direction and performance
12:13 15 Sep 2015

What is the cause of the severe slowdown when iterating bash arrays backwards?

Example:

time bash -c 'arr=();for i in {1..100000}; do arr+=( $i );done; echo "Straight"; i=0;while (( $i < 100000 )); do current_element=${arr[$i]}; ((i++));done'

Straight

real    0m0.270s
user    0m0.269s
sys    0m0.002s

time bash -c 'arr=();for i in {1..100000}; do arr+=( $i );done; echo "Reverse"; i=99999;while (( $i > 0 )); do current_element=${arr[$i]}; ((i--));done'

Reverse

real    0m25.569s
user    0m25.589s
sys    0m0.008s

Also,

${arr[i-1]} + ${arr[i]}

is much faster than

${arr[i]} + ${arr[i-1]}
bash --version

Output:

GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)
arrays bash performance iteration direction