C++ string.empty() 或 string.size() == 0 哪个更快?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17539626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:16:30  来源:igfitidea点击:

Which is faster, string.empty() or string.size() == 0?

c++performancec++11string

提问by Jatin Ganhotra

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?

讨论是关于使用mystring.empty()来验证字符串是否为空。现在,我同意可以说它string.empty()是更冗长和可读的代码,但它有任何性能优势吗?

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.

这两个答案都支持我的说法,即string.empty()string.size() == 0.

I still want to be sure, if there are any implementations of stringthat keep an internal boolean flagto validate if a string is empty or not?

我仍然想确定,是否有任何实现string可以保留内部布尔标志来验证字符串是否为空?

Or there are other ways that some implementations use, that would nullify my claim??

或者还有一些实现使用的其他方式,这会使我的主张无效?

回答by chris

The standard defines empty()like this:

该标准定义empty()如下:

bool empty() const noexcept;
Returns: size() == 0.

bool empty() const noexcept;
返回: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.

这就是说,empty()是明确和明确的。为了可读性,您应该更喜欢它size() == 0(或!size())。

回答by Tony Delroy

Now, this is a pretty trivial matter, but I'll try to cover it exhaustively so whatever arguments are put by colleagues aren't likely to take you by surprise....

现在,这是一件非常微不足道的事情,但我会尽量详尽地介绍它,这样同事们提出的任何论点都不可能让您感到意外......

As usual, if profiling proved you really reallyhad to care, measure: there couldbe a difference (see below). But in a general code review situation for not-proved-problematically-slow code, the outstanding issues are:

像往常一样,如果剖析证明你真的真的不得不去关心,测量:有可能出现差异(见下文)。但是在未证明有问题的慢代码的一般代码情况下,突出的问题是:

  • in some other containers (e.g. C++03 lists but not C++11), size()was less efficient than empty(), leading to some coding tips to prefer empty()over size()in general so that if someone needed to switch the container later (or generalise the processing into a template where the container type may vary) no change needs to be made to retain efficiency.

  • does either reflect a more natural way to conceive of the test? - not just what you happened to think of first, or size()because you're not as used to using empty(), but when you're 100% focused on the surrounding code logic, does size()or empty()fit in better? For example, perhaps because it's one of several tests of size()and you like having consistency, or because you're implementing a famous algorithm or formula that's traditionally expressed in terms of size: being consistent might reduce the mental noise/effort in verifying the implementation against the formula.

  • 在一些其他的容器(例如C ++ 03列表但不是C ++ 11),size()比效率较低empty(),导致一些编码提示偏爱empty()超过size()一般,这样,如果有人需要切换后的容器(或概括的加工成容器类型可能不同的模板)无需更改即可保持效率。

  • 是否反映了一种更自然的测试方式?- 不只是您碰巧首先想到的,或者size()因为您不习惯使用empty(),而是当您 100% 专注于周围的代码逻辑时,是否更适合size()或更empty()适合?例如,也许是因为它是几个测试之一size()并且您喜欢具有一致性,或者因为您正在实施传统上以大小表示的著名算法或公式:一致可能会减少验证实施时的心理噪音/努力公式。

Most of the time the factors above are insignificant, and raising the issue in a code review is really a waste of time.

大多数情况下,上述因素都无关紧要,在代码中提出问题确实是在浪费时间。

Possible performance difference

可能的性能差异

While the Standard requires functional equivalence, some implementations mightimplement them differently, though I've struggled and so far failed to document a particularly plausible reason for doing so.

虽然标准要求功能等效,但一些实现可能会以不同的方式实现它们,尽管我一直在努力并且迄今为止未能记录这样做的特别合理的原因。

C++11 has more constraints than C++03 over behaviours of other functions that impact implementation choices: data()must be NUL terminated (used to be just c_str()), [size()]is now a valid index and must return a reference to a NUL character. For various subtle reasons, these restrictions make it even more likely that empty()will be no faster than size().

对于影响实现选择的其他函数的行为,C++11 比 C++03 具有更多约束:data()必须以 NUL 终止(以前只是c_str()),[size()]现在是有效索引,并且必须返回对 NUL 字符的引用。由于各种微妙的原因,这些限制使得它更有可能empty()不会比size().

Anyway - measure if you have to care.

无论如何 - 衡量你是否需要关心。