哪个更快/更高效? [英] Which is quicker/more efficient?

查看:124
本文介绍了哪个更快/更高效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在学习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.

解决方案

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.

这篇关于哪个更快/更高效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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