Search code examples
namespacestclupvar

Expected TCL: upvar vs namespace variable performance


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.


Solution

  • 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.