if(str1 == str2)与if(str1.length()== str2.length()&& str1 == str2) [英] if(str1==str2) versus if(str1.length()==str2.length() && str1==str2)

查看:53
本文介绍了if(str1 == str2)与if(str1.length()== str2.length()&& str1 == str2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过另一本代码中的第二本,并且我想进行这种长度比较可以提高代码的生产率.它在解析器中用于具有特定词典的脚本语言:单词长4至24个字母,平均7-8个字母,字母包括26个拉丁字母以及"@","$"和"_".

I've seen second one in another's code and I suppose this length comparison have been done to increase code productivity. It was used in a parser for a script language with a specific dictionary: words are 4 to 24 letters long with the average of 7-8 lettets, alphabet includes 26 latin letters plus "@","$" and "_".

长度比较用于转义==运算符,用于处理STL字符串,这显然比简单的整数比较要花更多的时间.但是同时,给定字典中的第一个字母分布比单词大小的分布要宽,因此比较字符串的两个第一个字母通常比该字符串的大小更不同.这样就不需要进行长度比较.

Length comparison were used to escape == operator working with STL strings, which obviously takes more time then simple integer comparison. But in the same time first letter distribution in the given dictionary is simply wider than a distribution of words size, so two first letters of comparing strings will be generally more often different, than the sizes of that strings. That makes length comparison unnecessary.

我已经进行了一些测试,这就是我发现的:在测试两个随机字符串比较一百万次时,第二种方法要快得多,因此长度比较似乎很有帮助.但是在一个正在运行的项目中,它在调试模式下的运行速度甚至更慢,而在发布模式下的运行速度甚至不足.

I've ran some tests and that is what I've found out: While testing two random strings comparison million times, second way is much faster, so length comparison seems to be helpful. But in a working project it works even slower in a debug mode and insufficiantly faster in a release mode.

所以,我的问题是:为什么长度比较可以加快比较速度,为什么会减慢速度?

So, my question is: why length comparison can fasten the comparison and why can it slow it down?

UPD:我也不喜欢第二种方式,但是这样做是有原因的,我想,我想知道这是什么原因.

UPD: I don't like that second way either, but it had been done for a reason, I suppose, and I wonder, what is this reason.

UPD2:认真地说,问题不在于如何做到最好.在这种情况下,我什至不使用STL字符串.毫无疑问,长度比较是不必要的,而且是错误的.等等.奇怪的是-在某些测试中,它确实确实会稍微好一些.这怎么可能?

UPD2: Seriously, the question is not how to do best. I'm not even using STL strings in this case anymore. There's no wonder that length comparison is unnecessary and wrong etc. The wonder is - it really tends to work slightly better in one certain test. How is this possible?

推荐答案

在您的随机测试中,字符串可能足够长以显示增益,而在实际情况下,您可能会处理较短的字符串和两个比较的常数因子不执行测试的字符串比较部分不会获得任何收益.

In your random test the strings might have been long enough to show the gain while in your real case you may deal with shorter strings and the constant factor of two comparison is not offset by any gain in not performing the string comparison part of the test.

这篇关于if(str1 == str2)与if(str1.length()== str2.length()&& str1 == str2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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