高效的运营商+

bbt*_*trb 7 c++ operator-overloading

我必须计算大量的3d向量,并使用带有重载运算符+和运算符*的向量类与单独组件的总和进行比较,显示大约三倍的性能差异.我知道假设差异必须是由于在重载运算符中构造对象.

如何避免施工并提高性能?

我特别困惑,因为以下基本上是afaik基本上做标准的方式,我希望编译器优化它.在现实生活中,总和不是在循环内完成的,而是在相当大的表达式(总可执行的几十MB)中总结不同的向量,这就是为什么在下面使用operator +的原因.

class Vector 
{
   double x,y,z;
   ...
   Vector&  
   Vector::operator+=(const Vector &v)
   {
       x += v.x;
       y += v.y;
       z += v.z;
       return *this;
   }

   Vector  
   Vector::operator+(const Vector &v)
   {
       return Vector(*this) += v; // bad: construction and copy(?)
   }

   ...
}

// comparison
double xx[N], yy[N], zz[N];
Vector vec[N];

// assume xx, yy, zz and vec are properly initialized
Vector sum(0,0,0);
for(int i = 0; i < N; ++i)
{
    sum = sum + vec[i];
}

// this is a factor 3 faster than the above loop
double sumxx = 0;
double sumyy = 0;
double sumzz = 0;
for(int i = 0; i < N; ++i)
{
    sumxx = sumxx + xx[i];
    sumyy = sumyy + yy[i];
    sumzz = sumzz + zz[i];
}
Run Code Online (Sandbox Code Playgroud)

任何帮助是极大的赞赏.

编辑: 谢谢大家的好评,我现在的表现处于同一水平.@ Dima's特别是@ Xeo的回答就是这个伎俩.我希望我能够多次回答"接受".我也会测试其他一些建议.

Xeo*_*Xeo 7

文章对如何优化等运营商一个很好的论证+,-,*,/.在以下方面
实现operator+这样的免费功能operator+=:

Vector operator+(Vector lhs, Vector const& rhs){
    return lhs += rhs;
}
Run Code Online (Sandbox Code Playgroud)

请注意lhsVector是如何复制而不是引用.这允许编译器进行优化,例如复制省略.
文章传达的一般规则:如果需要副本,请在参数中进行,因此编译器可以进行优化.本文不使用此示例,而是使用operator=复制和交换习惯用法.