根据规范/实现,访问命名空间变量与 upvar 之间是否存在预期差异。
我必须使用回调函数。我不能只是传递一个论点。经验上,upvar 获胜。但在所有合理的情况下,这是预期的吗?
谢谢。
最佳答案
当然是。全范围引用比 upvar
快比 variable
更快的引用引用。
要找出答案,命令 'time' 是您的 friend :
namespace eval toto {
proc cb_upvar {varname} {
upvar $varname var
incr var
}
proc cb_scoped {varname} {
incr $varname
}
proc cb_variable {varname} {
variable $varname
incr $varname
}
}
proc benchmark {cmd} {
set toto::totovar 1
time $cmd 100
puts -nonewline "[lindex $cmd 0] =>\t"
puts [time $cmd 20000000]
}
puts [info tclversion]
benchmark {toto::cb_scoped ::toto::totovar}
benchmark {toto::cb_variable totovar}
benchmark {toto::cb_upvar totovar}
输出:
toto::cb_scoped => 0.47478505 microseconds per iteration
toto::cb_variable => 0.7644891 microseconds per iteration
toto::cb_upvar => 0.6046395 microseconds per iteration
Rem:需要大量的迭代才能获得一致的结果。
关于namespaces - 预期 TCL : upvar vs namespace variable performance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48687557/