返回const std :: string真的比非const慢吗? [英] is returning a const std::string really slower than non-const?

查看:53
本文介绍了返回const std :: string真的比非const慢吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个问题中,用户评论说,返回const std :: string会丢失移动构造效率,并且速度较慢。

In another question a user made a comment that returning a const std::string loses move construction efficiency and is slower.

分配该方法的返回字符串是否确实如此:

Is it really true that assigning a string of return of this method:

const std::string toJson(const std::string &someText);

const std::string jsonString = toJson(someText);

...确实比非const版本慢:

... is really slower than the non-const version:

std::string toJson(const std::string &str);

std::string jsonString = toJson(someText);

在这种情况下,移动施工效率的含义是什么?

And what is the meaning of move-construction efficiency in this context?

我之前从未听说过该限制,并且不记得在分析器中看到过该限制。但是我很好奇。

I've never heard of that limitation before and do not remember having seen that in the profiler. But I'm curious.

编辑:有一个建议的问题询问:什么是移动语义?。虽然某些解释当然与效率有关,但它解释了什么移动语义的含义,但没有解决为什么返回const值可能对性能产生负面影响。 / p>

There is a suggested question asking: What is move semantics?. While some of the explanations of course relate to efficiency, it explains what move semantics means, but does not address why returning a const value can have negative side effects regarding performance.

推荐答案

请考虑以下功能:

std::string f();
std::string const g();

两者之间没有区别:

std::string s1 = f();
std::string s2 = g();

我们现在保证了复制省略,在这两种情况下,我们都直接构造为结果对象。没有副本,没有动静。

We have guaranteed copy elision now, in both of these cases we're constructing directly into the resulting object. No copy, no move.

但是,两者之间有很大的区别:

However, there is a big difference between:

std::string s3, s4;
s3 = f(); // this is move assignment
s4 = g(); // this is copy assignment

g()可能是一个右值,但它是一个 const 右值。它无法绑定到移动赋值运算符采用的 string& 参数,因此我们回到 copy 赋值运算符,其 string const& 参数可以愉快地接受一个右值。

g() may be an rvalue, but it's a const rvalue. It cannot bind to the string&& argument that the move assignment operator takes, so we fall back to the copy assignment operator whose string const& parameter can happily accept an rvalue.

对于像这样的类型,复制绝对比移动慢字符串,其中移动是恒定时间,复制是线性的,可能需要分配。

Copying is definitely slower than moving for types like string, where moving is constant time and copying is linear and may require allocation.

不返回const值。

Don't return const values.

最重要的是,对于非类类型:

On top of that, for non-class types:

int f();
int const g();

这两个实际上是相同的,都返回 int 。您不能返回非类类型的const prvalue,但是可以返回类类型的const prvalue,这是一种奇怪的语言。假装您也不能做后者,因为您不应该这样做。

These two are actually the same, both return int. It's an odd quirk of the language that you cannot return a const prvalue of non-class type but you can return a const prvalue of class type. Easier to just pretend you can't do the latter either, since you shouldn't.

这篇关于返回const std :: string真的比非const慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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