2016-12-08 77 views
1

假設我有一個Tcl字典。我想要最快的方法來獲取字典的最後輸入的鍵(不是值)。 理論上,我可以使用:lindex [ dict keys $dict ] end
有沒有人知道別的,這是更快?Tcl中最後一個字典的最快路徑

+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

我看到[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" 
相關問題