Bash 访问数组元素时的性能注意事项
我目前正在业余时间学习一些bash,并利用bash进行了一些简单的编码挑战。在解决上一个挑战时,我发现了一些奇怪的优化问题:Bash 访问数组元素时的性能注意事项,bash,Bash,我目前正在业余时间学习一些bash,并利用bash进行了一些简单的编码挑战。在解决上一个挑战时,我发现了一些奇怪的优化问题: # read the number of input values read N # read all input values into an array readarray -n $N P # sort the input array in an ascending order PS=($(printf "%s\n" ${P[@]} | sort -n)) #
# read the number of input values
read N
# read all input values into an array
readarray -n $N P
# sort the input array in an ascending order
PS=($(printf "%s\n" ${P[@]} | sort -n))
# init the current minimum distance of two horses by the max input value plus one
Min=10000001
# iterate over the ascending sorted array
# and find the minimum distance
for ((i = 1; i < N; i++)); do
# compute the difference between the current and the last
#D=$((PS[i]-PS[i-1]))
D=$((-PS[i-1]+PS[i]))
if [ $D -le $Min ]; then
Min=$D
fi
done
# finally print the minimum distnce
echo $Min
#读取输入值的数量
阅读
#将所有输入值读入数组
readarray-n$n P
#按升序对输入数组排序
PS=($(printf“%s\n”${P[@]}排序-n))
#用最大输入值加上一,初始化当前两匹马的最小距离
最小值=10000001
#迭代升序排序数组
#然后找到最小距离
(i=1;i
以某种方式访问PS[i]并紧接着访问PS[i-1]会导致测试用例中10万个输入值耗尽时间。然而,以相反的顺序访问完全相同的数组元素会导致测试用例正常运行。非关联数组访问应该需要O(1)个时间,那么访问顺序如何可能影响运行时性能呢?是否有一些bash魔法在我不知道的内部进行(比如数组被实现为单链表或类似的东西??)bash数组不是C意义上的数组,因为您可以使用稀疏数组而不浪费内存:
a=([1]=0 [100000000]=2 [10000000000]=3)
普通数组允许O(1)访问,因为索引指定的内存位置可以通过O(1)中的公式计算,这通常是因为数组存储在连续内存中,您只需要计算偏移量。通常,稀疏数组是使用链表实现的,即使它们是使用hashmaps之类的其他工具实现的。一条油嘴滑舌的评论:如果您担心性能,请不要使用bash编程。大家都知道它很慢根据对这个问题的回答,正如您所怀疑的,Bash中的数组是链表。Bash数组和映射是关联数组,即具有kv对的链表。所以在最坏的情况下,数组需要O(n)时间,映射也需要O(n)时间。