轻灵,内省,质朴,有为

for和foreach编译成字节码之后的速度比较

+1 投票

参见:https://www.tcler.net/41/tcl中for和foreach的速度比较

简单结论:

  • 编译成字节码之后速度可以提高5~6倍;
  • Tcl 8.5中foreach比for快1.5倍左右;
  • Tcl 8.6中foreach和for速度相当;
速度比较结果:
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语句字节码的优化。

速度比较结果:Tcl 8.6
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

测试代码如下:

Code: for-vs-foreach.tcl
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
}


最新提问 9月 22, 2015 分类:语法命令 | 用户: 风行水上 (-30 分)

登录 或者 注册 后回答这个问题。

...