Is there an expected, by spec/implementation, difference between accessing namespace variables vs. upvar. I have to use a call-back function. I cannot just pass an argument.Empirically, upvar wins. But is that expected, in all reasonable case? Thanks.
Asked
Active
Viewed 252 times
1 Answers
2
Yes definitely. fully scoped reference is faster than upvar
reference which is faster than variable
reference.
To find-out, the command 'time' is your 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}
Output:
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: the huge number of iterations is required to get consistent result.

A. Richard
- 240
- 1
- 6
-
Empirically, that what I got, but I was wondering if this is a fluke, or expected. – user1134991 Feb 09 '18 at 16:57
-
1It depends really on how many times you're using a variable in a procedure. If just once, fully scoped is fastest. The other two options (which are semantically different from each other in key ways) become much more useful once you use a variable multiple times. But using `time` to find the truth is _great_ advice. – Donal Fellows Feb 10 '18 at 08:51
-
@DonalFellows is correct about highlighting that the choice shouldn't be only about speed but take into account the usage in the procedure. – A. Richard Feb 12 '18 at 12:38
-
I am using the variable over and over again, as the procedure may be called millions of times. – user1134991 Feb 13 '18 at 16:35