通往Tcl最后一个字的关键路线

时间:2016-12-08 19:15:49

标签: dictionary tcl

我们说我有一个Tcl词典。我希望以最快的方式获得最后输入的dict键(而不是值)。 从理论上讲,我可以使用:lindex [ dict keys $dict ] end
有没有人知道其他什么,哪个更快?

2 个答案:

答案 0 :(得分:1)

这很快:

% set data {a 1 b 2 c 3}
a 1 b 2 c 3
% proc p1 {} {dict get $::data [lindex [dict keys $::data] end]}
% time {p1} 100000
1.87782 microseconds per iteration

但是你可以通过记住最后一个键来减少大约一微秒:

oo::object create mydict
oo::objdefine mydict {
    variable data last
    method add args {
        lappend data {*}$args
        set last [lindex [dict keys $data] end]
    }
    method getLast {} {
        dict get $data $last
    }
} 

% mydict add a 1 b 2 c 3
c
% time {mydict getLast} 100000
0.82731 microseconds per iteration

文档: create (method of oo::class)dictlappendlindexmethod (object configuration subcommand)procoo::objdefine (object definition command)oo::object (class of objects)settimevariable (object slot subcommand){*} (syntax)

答案 1 :(得分:1)

我看到[lindex $data end-1]更快。

tclsh last.tcl
time_list : 1.0693949999999999 microseconds per iteration
time_dict : 279.470543 microseconds per iteration

last.tcl

set data [dict create]
for {set i 0} {$i < 10000} {incr i} {
        dict set data "key_$i" $i
}

set time_dict [time {
        set last_key [lindex [dict keys $data] end]
} 1000]


set time_list [time {
        set last_key [lindex $data end-1]
} 1000]

puts "time_list : $time_list"
puts "time_dict : $time_dict"