在 C 中比较字符串的最快方法 [英] Fastest way of comparing strings in C

查看:31
本文介绍了在 C 中比较字符串的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 C 中是否有比使用 strcmp() 更快的方法来比较字符串,尤其是当我必须将一个字符串与 中的多个预定义字符串进行比较时switch 语句 时尚.在我的应用程序中,要比较的字符串有时可以达到 1000 个字符,所以只是想 strcmp() 是否足够,或者是否存在我不熟悉的更好和有效的方法.我实际上正在开发一个低功耗嵌入式物联网项目,其中更多的 CPU 周期会消耗电力.

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 strings in a switch statement fashion. In my application, the string to be compared can sometimes go as big as 1000 chars, so was just thinking if strcmp() is sufficient enough or if there exists better and efficient way which I am not familiar with. I am actually working on a low power embedded IoT project where more CPU cycles cost power.

推荐答案

这听起来好像问题与 strcmp 本身有很大关系,而在于你如何使用它.

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

将字符串与预定义字符串表进行比较的最快方法是确保字符串按字母顺序排序,然后使用二进制搜索.其中 strcmp 充当比较函数.C 标准 bsearch 在嵌入式系统上可能可行,也可能不可行.否则,自己实现是相当简单的.

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.

使用固定长度的字符串,您可以改用 memcmp 来稍微提高性能 - 这样您就不必检查空终止.但这确实是一个微优化.

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.

这篇关于在 C 中比较字符串的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆