Fastest way of comparing strings in C

前端 未结 1 994
北恋
北恋 2021-01-24 12:12

I wanted to know if there are even faster ways of comparing strings in C than using strcmp(), especially when I have to compare a string with multiple pre-defined s

相关标签:
1条回答
  • 2021-01-24 12:56

    It doesn't sound as if the problem has as much to do with strcmp itself, as how you use it.

    The fastest way to compare strings against a table of pre-defined strings, is to ensure that the strings are sorted alphabetically, then use binary search. Where strcmp acts as the comparison function. C standard bsearch may or may not be feasible on an embedded system. Otherwise, it is fairly simple to implement yourself.

    That is, unless the number of strings are vast. Then at some point, some manner of hash table will perform better than searching. To give an exact answer of what performs best, one needs all the details of the data.

    With fixed-length strings you can improve performance ever so slightly by using memcmp instead - that way you don't have to check against null termination. But that's really a micro-optimization.

    0 讨论(0)
提交回复
热议问题