"Steven W. Orr" wrote:
Hold on there Buffalo Bob!
    Umm... okay.
There is no big difference between a strlen and
a strcmp.
    Agreed.  But there is a significant difference between (say) 12 strcmp's vs. 1 strlen and 2 strcmp's.  That is, suppose you are checking for a match on 12 different strings.  If a particular instance will match the last one, or match none at all (which could happen a lot if you're searching for something), then the "straightforward" method results in 12 different strcmp's.
    "My" method is usually much quicker, and easy to implement.  Take the strlen of the string (equiv. to one strcmp).  Then break out a switch statement.  Say there are two strings of the same length you are comparing against.  Now you only do another 2 strcmp's.  I just went from walking the string 12 times to just 3 times in this particular case.  YMMV, but (as I said) if you have more that just 2 strings that vary in length, the method I outlined is likely to be useful.
The way you're describing it, you're
actually walking the strings twice: once to see how long they are and then
a second time (if they're the right length, I'll grant you) to see if
their value is the match.
    Your "(if they're the right length, I'll grant you)" is the key.  It avoids walking the string multiple times.
The *only* way to minimize the cost of the individual character accesses
is to write a custom finite state machine.
    I never said I was trying to minimize the string comparisons.  I was trying to make it quicker without making it too complicated.  My second suggestion comes closer to a minimal solution, but implies a more complex solution.  I've found that in practive my method is both easy to implement and worthwhile.

    The cost is greatly reduced from the "strcmp each string" method because although there is overhead equivalent to walking the string once, you use strcmp on (potentially) a lot fewer strings (depending on the dataset).

--
Bob Bell                Compaq Computer Corporation
Software Engineer       110 Spit Brook Rd - ZKO3-3U/14
TruCluster Group        Nashua, NH 03062-2698
[EMAIL PROTECTED]     603-884-0595
 


Reply via email to