Reputation: 1149
I have a string, and I want to check whether it begins with a certain character (# in this case). I'd like to know the most efficient way of doing this!
What I'm thinking of is if {[string compare -length 1 $string "#"]}
, because it might use strcmp() which will probably be one of the fastest ways to achieve this.
What I think might also be possible is if {[string index $string 1] == "#"}
, because it might do *string == '#' which will probably also be very fast.
What do you think?
Upvotes: 9
Views: 16223
Reputation: 137567
The fastest method of checking whether a string starts with a specific character is string match
:
if {[string match "#*" $string]} { ... }
The code to do the matching sees that there's a star after the first character and then the end of the string, and so stops examining the rest of $string
. It also doesn't require any allocation of a result (other than a boolean one, which is a special case since string match
is also bytecode-compiled).
Upvotes: 22