为什么整数比较比字符串比较快? [英] Why is integer comparison faster then string comparison?
问题描述
在几本书中,我发现了有关避免使用字符串进行值比较(尤其是在循环中)的注释,因为字符串比较要慢得多(使用std :: string).但是,为什么呢?
I found comments about avoiding strings for the comparison of values (especially in loops) in a few books because string comparison is a lot slower (using std::string). But why exactly is that?
是因为cpu中的整数单位工作得更快吗?
Is it because integer units in the cpu are working faster?
我猜字符串应该以字节为单位,所以字节比较不会同样地完成这项工作吗?
Strings should be in byte I guess, so wouldn't a byte comparison do the job equally?
谢谢!
推荐答案
对于整数,机器级别上存在可以在一个周期内执行比较的指令.
With an integer, there exist instructions on the machine level which can perform a comparison in one cycle.
但是,字符串由很多字符组成.为了比较字符串,在最坏的情况下,您必须查看字符串的每个字符.
A string, however, consists of a lot of characters. In order to compare strings, you, in the worst case, have to look at every character of the strings.
实际上,当您比较字符串时,很可能会对字符串中的每个字符使用整数比较.您可能会发现,与比较两个整数相比,这很快就能变成大量的比较.
In fact, when you compare strings, you're most likely using an integer comparison for each character in the string. You can probably see how this quickly can turn into a lot of comparisons as compared to comparing two integers.
示例:如果要比较1073741822与1073741823.
Example: If you want to compare 1073741822 with 1073741823.
- 字符串比较:您必须逐一比较每个数字.这是10次比较,因为整数仅相差最后一位.
- 整数比较:您可以在一个比较中进行此操作,与String比较相比可以保存9个比较.
- String comparison: You have to compare each of the digits one by one. This is 10 comparisons, since the integers only differ by the last digit.
- Integer comparison: You can do this in one comparison, saving 9 comparisons as compared to the String comparison.
自然,这有点简化了,但是希望可以理解这一点.
This is a bit simplified, naturally, but hopefully gets the point across.
这篇关于为什么整数比较比字符串比较快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!