【问题标题】:Expected TCL: upvar vs namespace variable performance预期的 TCL:upvar 与命名空间变量的性能
【发布时间】:2018-02-08 14:13:10
【问题描述】:

根据规范/实现,访问命名空间变量与 upvar 之间是否存在预期差异。 我必须使用回调函数。我不能只传递一个论点。根据经验,upvar 获胜。但在所有合理的情况下,这是预期的吗? 谢谢。

【问题讨论】:

    标签: namespaces tcl upvar


    【解决方案1】:

    是的,当然。全范围引用比 upvar 引用快,后者比 variable 引用快。

    要找出答案,命令“时间”是你的朋友:

    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:需要大量的迭代才能获得一致的结果。

    【讨论】:

    • 根据经验,这是我得到的,但我想知道这是侥幸还是预期。
    • 这实际上取决于您在过程中使用变量的次数。如果只有一次,完全范围是最快的。一旦您多次使用变量,其他两个选项(在关键方面在语义上彼此不同)变得更加有用。但是使用time 来寻找真相是伟大的建议。
    • @DonalFellows 正确地强调了选择不应该只是速度,而是要考虑到过程中的使用情况。
    • 我一遍又一遍地使用该变量,因为该过程可能会被调用数百万次。
    猜你喜欢
    • 2012-08-26
    • 2015-04-22
    • 2021-03-21
    • 2012-07-22
    • 2011-05-21
    • 2018-09-25
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多