哪个更快/更有效率?
目前正在学习 C++ 的效率,并想知道方法中返回参数的效率。
想象一个带有 add 方法的 Vector3f 类。
代码一:
Vector3f Vector3f::add(const Vector3f &rhs) const {
Vector3f result;
result.x(x() + rhs.x());
result.y(y() + rhs.y());
result.z(z() + rhs.z());
return result;
}
代码二:
Vector3f Vector3f::add(const Vector3f &rhs) const {
return Vector3f(
x() + rhs.x(),
y() + rhs.y(),
z() + rhs.z());
}
我知道第二个代码段效率更高,我希望有人能给我一个明确的答案。我确信这与临时对象有关。
Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.
Imagine a Vector3f class with an add method.
Code One:
Vector3f Vector3f::add(const Vector3f &rhs) const {
Vector3f result;
result.x(x() + rhs.x());
result.y(y() + rhs.y());
result.z(z() + rhs.z());
return result;
}
Code Two:
Vector3f Vector3f::add(const Vector3f &rhs) const {
return Vector3f(
x() + rhs.x(),
y() + rhs.y(),
z() + rhs.z());
}
I know that the second code segment is more efficient, and I was hoping someone could give me a definitive answer as to why. I'm sure it's something to do with temporary objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可能与返回值优化(RVO)有关。因为第二种形式在返回对象时构造对象,所以编译器可以(并且通常会)通过直接在调用者的上下文中构造对象来跳过复制构造函数。
第一种形式也可以以类似的方式进行优化,但我经常看到编译器优化后者而不是前者。
It probably has to do with the return-value optimisation (RVO). Because the second form constructs the object as it returns it, the compiler is allowed to (and usually will) skip the copy-constructor by constructing the object directly in the caller's context.
The first form can also be optimised in similar fashion, but I've often seen compilers optimise the latter and not the former.
实际上,它与初始化有更多关系:当您“默认构造”您的
Vector3f 结果
时,x
、y
、z
成员将被初始化。您并不总是能够控制其成本,尤其是对于“重度”会员。使用所有成员值调用构造函数允许对象第一次正确初始化其成员。
但如果您确实想节省一些中间步骤,您可以在类
Vector3f
上创建一个变体,从而消除对临时的需要:并像这样使用它
Actually, it has more to do with initialization: when you 'default construct' your
Vector3f result
, thex
,y
,z
members will be initialized. You don't always control the cost of that, especially with 'heavy' members.Calling a constructor with all member values allows the object to initialize it's members first time right.
But if you really want to save some intermediate steps, you can create a mutator on the class
Vector3f
, eliminating the need for a temporary:and use it like
想知道编译器如何做事情很好,但我假设你明白几乎总是有更大的“鱼要炸”。
在我看来,很多人从没有太多使用大型真实软件经验的教师和作者那里获得了关于性能的想法。
我不知道还能如何解释对微观问题的关注,
人们似乎不知道自己什么时候在猜测,即使猜测是有根据的。
因此,FWIW,这里有一些关于性能的常见概念。
It's fine to wonder how the compilers do things, but I assume you understand there are almost always bigger "fish to fry".
It seems to me lots of people get their ideas about performance from teachers and authors who haven't had much experience with big gnarly real software.
I don't know how else to explain the concentration on micro-issues,
and that people don't seem to know when they are guessing, even if the guesses are educated.
So, FWIW, here are some common conceptions about performance.