'Tcl: best way to test for empty list
Sorry, that's a very trivial question, but it seems to be so trivial that I can't find any recommendation: What is the best way in Tcl to test whether a list is empty? I would go for if {$myList eq ""} ..., or is there a better way? Thanks for your help!
Solution 1:[1]
I just want to share some test code which shows that if {$myList eq ""}... can be much slower than if {![llength $myList}} ...:
set repeats 10
foreach n {10 100 1000 10000 20000} {
puts "n = $n"
puts [time {
set l [list]
for {set i 0} {$i < $n} {incr i} {
lappend l $i
}
} $repeats]
puts [time {
set l [list]
for {set i 0} {$i < $n} {incr i} {
lappend l $i
if {![llength $l]} {
puts "empty (llength)"
}
}
} $repeats]
puts [time {
set l [list]
for {set i 0} {$i < $n} {incr i} {
lappend l $i
if {$l eq ""} {
puts "empty (eq)"
}
}
} $repeats]
}
Here is the output; for each value of n: baseline (no check), check with llength, check with eq:
n = 10
5.0 microseconds per iteration
14.1 microseconds per iteration
14.0 microseconds per iteration
n = 100
40.6 microseconds per iteration
44.0 microseconds per iteration
105.8 microseconds per iteration
n = 1000
374.4 microseconds per iteration
440.7 microseconds per iteration
6240.1 microseconds per iteration
n = 10000
3534.4 microseconds per iteration
4485.8 microseconds per iteration
667206.0 microseconds per iteration
n = 20000
7576.7 microseconds per iteration
9051.9 microseconds per iteration
2761285.3 microseconds per iteration
I would guess that the solution using if {$l eq ""}... is very slow since does a conversion from a list to a string every time the check is done. Or is there a different explanation?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
