$ ksh -c 'i=5; for x in {1..$i}; do echo "$x"; done'12345$ ksh -c 'echo $KSH_VERSION'Version JM 93u+ 2012-02-29
$ bash -c 'i=5; for x in {1..$i}; do echo "$x"; done'{1..5}
这些不是结论。你必须查看每个结论背后的C代码才能得出结论。这更多的是关于我们如何使用这些机制来循环代码。大多数单个操作都足够接近相同的速度,以至于在大多数情况下这并不重要。但是像for (( i=1; i<=1000000; i++ ))这样的机制是许多操作,你可以直观地看到。每个循环的操作也比for i in $(seq 1 1000000)得到的要多得多。而这对你来说可能并不明显,这就是为什么做这样的测试是有价值的。
演示
# show that seq is fast$ time (seq 1 1000000 | wc)1000000 1000000 6888894
real 0m0.227suser 0m0.239ssys 0m0.008s
# show that {..} is fast$ time (echo {1..1000000} | wc)1 1000000 6888896
real 0m1.778suser 0m1.735ssys 0m0.072s
# Show that for loops (even with a : noop) are slow$ time (for i in {1..1000000} ; do :; done | wc)0 0 0
real 0m3.642suser 0m3.582ssys 0m0.057s
# show that echo is slow$ time (for i in {1..1000000} ; do echo $i; done | wc)1000000 1000000 6888896
real 0m7.480suser 0m6.803ssys 0m2.580s
$ time (for i in $(seq 1 1000000) ; do echo $i; done | wc)1000000 1000000 6888894
real 0m7.029suser 0m6.335ssys 0m2.666s
# show that C-style for loops are slower$ time (for (( i=1; i<=1000000; i++ )) ; do echo $i; done | wc)1000000 1000000 6888896
real 0m12.391suser 0m11.069ssys 0m3.437s
# show that arithmetic expansion is even slower$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; i=$(($i+1)); done | wc)1000000 1000000 6888896
real 0m19.696suser 0m18.017ssys 0m3.806s
$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; ((i=i+1)); done | wc)1000000 1000000 6888896
real 0m18.629suser 0m16.843ssys 0m3.936s
$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $((i++)); done | wc)1000000 1000000 6888896
real 0m17.012suser 0m15.319ssys 0m3.906s
# even a noop is slow$ time (i=1; e=1000000; while [ $((i++)) -le $e ]; do :; done | wc)0 0 0
real 0m12.679suser 0m11.658ssys 0m1.004s