Tcl中for和foreach的速度比较

先说简单结论:

  • foreach的速度比for
  • for比较慢的原因主要是因为多了条件判断语句和lindex语句
  • whilefor的速度相当
8.5.2
    1633 microseconds per iteration # foreach
    3170 microseconds per iteration # for
    2494 microseconds per iteration # foreach + expr
    2934 microseconds per iteration # foreach + lindex
    3777 microseconds per iteration # foreach + expr + lindex
    3211 microseconds per iteration # while
8.5.17
    1874 microseconds per iteration # foreach
    2952 microseconds per iteration # for
    2570 microseconds per iteration # foreach + expr
    3025 microseconds per iteration # foreach + lindex
    3708 microseconds per iteration # foreach + expr + lindex
    2937 microseconds per iteration # while
8.6.1
    2100 microseconds per iteration # foreach
    2773 microseconds per iteration # for
    2862 microseconds per iteration # foreach + expr
    3162 microseconds per iteration # foreach + lindex
    3804 microseconds per iteration # foreach + expr + lindex
    2739 microseconds per iteration # while

测试用代码

puts [info patch]

lassign $argv COUNT

set chars [split [string repeat x 4096] ""]

proc measure [list name body "N $COUNT"] {
  set time [lindex [uplevel [list time $body]] 0]
  puts [format "%8d microseconds per iteration # %s" $time $name ]
}

measure "foreach" {
  set n 0
  set N 4096
  foreach c $chars {
    set t $c
    incr n
  }
}

measure "for" {
  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 "foreach + expr" {
  set n 0
  set N 4096
  foreach c $chars {
    expr {$n<$N}
    set t $c
    incr n
  }
}

measure "foreach + lindex" {
  set n 0
  set N 4096
  foreach c $chars {
    set c [lindex $chars $n]
    set t $c
    incr n
  }
}

measure "foreach + expr + lindex" {
  set n 0
  set N 4096
  foreach c $chars {
    expr {$n<$N}
    set c [lindex $chars $n]
    set t $c
    incr n
  }
}

measure "while" {
  set n 0
  set N 4096
  while {$n<$N} {
    set c [lindex $chars $n]
    set t $c
    incr n
  }
}