string.empty()或string.size()== 0哪个更快? [英] Which is faster, string.empty() or string.size() == 0?
问题描述
最近,在一次讨论中,一位同行程序员要求我进行一些代码更改。我有类似的东西:
if(mystring.size()== 0)
//做点
else
//做其他事情
讨论是关于<$的使用c $ c> mystring.empty()来验证字符串是否为空。现在,我同意可以争论的是, string.empty()
是更冗长和可读的代码,但是它对性能有好处吗?
我做了一些挖掘,发现了与我的问题有关的以下两个答案:
这两个答案都支持了我的观点,即与 string相比,
。 string.empty()
更具可读性,并且不提供任何性能优势。 size()== 0
我仍然想确定是否有 string
的实现保留了内部布尔值标记以验证字符串是否为空?
或者某些实现使用其他方式可以使我的主张无效?
标准如下定义 empty()
:
bool empty()const noexcept;
返回:size()== 0。
您很难找到无法做到这一点的东西,由于两者都是恒定时间操作,因此任何性能差异都可以忽略不计。我希望它们都能在任何合理的实现上编译为完全相同的程序集。
也就是说, empty()
清晰明了。为了提高可读性,您最好使用 size()== 0
(或!size()
)。
Recently, during a discussion I was asked by a fellow programmer to do some code changes. I had something like:
if( mystring.size() == 0)
// do something
else
// do something else
The discussion was regarding the use of mystring.empty()
to validate if the string is empty. Now, I agree that it can be argued that string.empty()
is more verbose and readable code, but are there any performance benefits to it?
I did some digging and found these 2 answers pertaining to my question:
Both the answers buttress my claim that the string.empty()
is just more readable and doesn't offer any performance benefits, compared to string.size() == 0
.
I still want to be sure, if there are any implementations of string
that keep an internal boolean flag to validate if a string is empty or not?
Or there are other ways that some implementations use, that would nullify my claim??
The standard defines empty()
like this:
bool empty() const noexcept;
Returns: size() == 0.
You'd be hard-pressed to find something that doesn't do that, and any performance difference would be negligible due to both being constant time operations. I would expect both to compile to the exact same assembly on any reasonable implementation.
That said, empty()
is clear and explicit. You should prefer it over size() == 0
(or !size()
) for readability.
这篇关于string.empty()或string.size()== 0哪个更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!