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

查看:290
本文介绍了在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.

使用固定长度的字符串,使用<$可以稍微提高性能。 c $ c> memcmp 代替-这样,您就不必检查null终止了。但这确实是微观优化。

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天全站免登陆