在Tcl中使用唯一值填充列表的更快的方法是什么?

SIM*_*MEL 2 performance tcl

我想创建一个唯一值列表.这些值来自不同的来源和.有两种方法可以填充我的最终列表.

将所有值放入然后执行lrmdups:

set finalList [list ]
foreach selcetion  $selectionList {
    regexp {(\d+):(\d+)} $selection -> start end
    for {set i $start} {$i <= $end} {incr i} {
        lappend finalList $i
    }
}
set finalList [lrmdups $finalList]
Run Code Online (Sandbox Code Playgroud)

或者检查列表中是否存在值,并且仅当它没有添加它时:

set finalList [list ]
foreach selcetion  $selectionList {
    regexp {(\d+):(\d+)} $selection -> start end
    for {set i $start} {$i <= $end} {incr i} {
        if {[lsearch $finalList $i] == -1} {
            lappend finalList $i
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这两种方法中哪一种更快?

pat*_*yts 5

使用time命令测试Tcl代码的性能.确保将代码放在一个过程中以获得字节编译的好处,然后使用time命令多次运行测试并获得每次迭代的平均时间.例如,这是一个示例,说明为什么应始终支持expr表达式.

% proc a {} {expr 1 + 2 + 3}
% proc b {} {expr {1 + 2 + 3}}
% time a 1000
4.491 microseconds per iteration
% time b 1000
0.563 microseconds per iteration
Run Code Online (Sandbox Code Playgroud)

为了处理特定的任务 - 我会将每个新值添加到一个数组中,让它吃掉重复项,然后在最后将它变成一个列表.

proc getUniques {wantedSize} {
    array set uniques {}
    while {[array size uniques] != $wantedSize} {
         set uniques([getNewValue]) {}
    }
    return [array names uniques]
}
Run Code Online (Sandbox Code Playgroud)