c++ - Efficient operator+ -


i have compute large sums of 3d vectors , comparison of using vector class overloaded operator+ , operator* versus summing of separate components shows performance difference of factor of three. know assume difference must due construction of objects in overloaded operators.

how can 1 avoid construction , improve performance?

i'm espacially puzzled, because following afaik standard way , expect compiler optimize this. in real life, sums not going done within loop in quite large expressions (several tens of mbs in total pre executable) summing different vectors, why operator+ used below.

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 , copy(?)    }     ... }  // comparison double xx[n], yy[n], zz[n]; vector vec[n];  // assume xx, yy, zz , vec initialized vector sum(0,0,0); for(int = 0; < n; ++i) {     sum = sum + vec[i]; }  // factor 3 faster above loop double sumxx = 0; double sumyy = 0; double sumzz = 0; for(int = 0; < n; ++i) {     sumxx = sumxx + xx[i];     sumyy = sumyy + yy[i];     sumzz = sumzz + zz[i]; } 

any appreciated.

edit: thank great input, have performance @ same level. @dima's , @xeo's answer did trick. wish mark more 1 answer "accepted". i'll test of other suggestions too.

this article has argumentation on how optimize operators such +, -, *, /.
implement operator+ free function in terms of operator+=:

vector operator+(vector lhs, vector const& rhs){     return lhs += rhs; } 

notice on how lhs vector copy , not reference. allowes compiler make optimizations such copy elision.
general rule article conveys: if need copy, in parameters, compiler can optimize. article doesn't use example, operator= copy-and-swap idiom.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -