参见:https://www.tcler.net/41/tcl中for和foreach的速度比较
简单结论:
8.5.2 1640 microseconds per iteration # foreach 3173 microseconds per iteration # for 2615 microseconds per iteration # foreach + expr 2922 microseconds per iteration # foreach + lindex 3936 microseconds per iteration # foreach + expr + lindex 3193 microseconds per iteration # while 341 microseconds per iteration # proc/foreach 523 microseconds per iteration # proc/for
如果是Tcl 8.6的话,for和foreach速度相当。这可能得益于Tcl 8.6中对for语句字节码的优化。
8.6.1 2091 microseconds per iteration # foreach 2765 microseconds per iteration # for 2829 microseconds per iteration # foreach + expr 3135 microseconds per iteration # foreach + lindex 3815 microseconds per iteration # foreach + expr + lindex 2747 microseconds per iteration # while 449 microseconds per iteration # proc/foreach 448 microseconds per iteration # proc/for 789 microseconds per iteration # proc/foreach-expr
测试代码如下:
proc proc/foreach {chars} { foreach c $chars { set t $c incr n } } proc proc/for {chars} { set n 0 set N 4096 for {set n 0 ; set N 4096} {$n<$N} {incr n} { set c [lindex $chars $n] set t $c } } measure "proc/foreach" { proc/foreach $chars } measure "proc/for" { proc/for $chars }