Bash数组迭代方向和性能
Bash array iteration direction and performance
有人可以解释一下向后迭代 bash 数组时速度严重下降的原因吗?
示例:
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
还有
${arr[i-1]} + ${arr[i]}
比
快很多
${arr[i]} + ${arr[i-1]}
感谢您的宝贵时间。
编辑:
bash --version
GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)
找到了一些关于此事的信息。
根据http://www.tldp.org/LDP/abs/html/arrays.html
Arrays in Bash are (circularly) linked lists of type string (char *).
我猜这意味着每次都从数组的开头寻找传递的元素,因此速度变慢了。 (eg:如果我们在i,为了到达i-1,我们应该从0开始找)
还找到了相关的 post,其中包含有关此事的更多信息:
http://spencertipping.com/posts/2013.0814.bash-is-irrecoverably-broken.html
有人可以解释一下向后迭代 bash 数组时速度严重下降的原因吗?
示例:
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
还有
${arr[i-1]} + ${arr[i]}
比
快很多${arr[i]} + ${arr[i-1]}
感谢您的宝贵时间。
编辑:
bash --version
GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu)
找到了一些关于此事的信息。
根据http://www.tldp.org/LDP/abs/html/arrays.html
Arrays in Bash are (circularly) linked lists of type string (char *).
我猜这意味着每次都从数组的开头寻找传递的元素,因此速度变慢了。 (eg:如果我们在i,为了到达i-1,我们应该从0开始找)
还找到了相关的 post,其中包含有关此事的更多信息: http://spencertipping.com/posts/2013.0814.bash-is-irrecoverably-broken.html