In general, #2 is going to be fastest. The
string equal command does simple character-by-character comparison, and terminates as soon as it finds a character that doesn't match. I suspect the
string compare would be a close second.
string match has to check for wildcards in the pattern argument, which will slow it down a little. And implicitly using
expr with the "==" test is slower because
expr also checks to see if the strings look like numbers, in which case it does a numerical comparison.
You could speed things up even more by directly using the Boolean value returned by
string equal rather than doing an explicit test:
Code:
if {[string equal $var 1]} {
..do something
}
In general, you can use the Tcl
time command to run timing experiments:
[tt]time
code ?iterations?[/tt]
For something like this, you'll need to run a lot of iterations to get valid data. Maybe 10000 or more. But the differences are going to be so slight (especially since none of these comparisons will take very long) that it will be difficult to get significant results.
As a quick test, I did the following on my Windows 2000 system with a 750Mhz Pentium III running Tcl 8.3.2:
Code:
% set val 1
1
% time {if {$val == 1} {set temp 1}} 1000000
3 microseconds per iteration
% time {if {[string equal $val 1] == 1} {set temp 1}} 1000000
7 microseconds per iteration
% time {if {[string equal $val 1]} {set temp 1}} 1000000
4 microseconds per iteration
% time {if {[string compare $val 1] == 0} {set temp 1}} 1000000
5 microseconds per iteration
% time {if {[string match $val 1] == 1} {set temp 1}} 1000000
7 microseconds per iteration
% time {if {[string match $val 1]} {set temp 1}} 1000000
5 microseconds per iteration
Interesting that in this case, using "==" was the fastest. I suspect that if we were comparing longer strings, we'd see
string equal pulling out in front.
But the most important point is: For a simple comparison like this, it just doesn't matter. Code it the way that is easiest to read and maintain. Tcl, like all interpreted languages, isn't going to be a speed demon. But with today's fast processors, it's usually "fast enough." Only if you're noticing significant delays or timing problems should you focus much on speed optimizations. And in those cases, you can use tools like Tcl's
time command to compare implementations. And, if it turns out to be too slow no matter how you implement a procedure in Tcl, you always have the option of implementing a Tcl command in C code. - Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax