开发者

Inlining an overloaded operator c++

Can/should an overloaded operator have to be inlined to gain better efficiency (wrt time or what开发者_运维技巧ever) if that operator will have to be used frequently?

I want to overload the '+' operator to add big vectors very frequently in my code. Hence the question.


Ideally, you'd profile your code and then decide what to inline. There really isn't much of a difference between when you decide to inline regular operators, over overloaded ones.


If you are adding big vectors, then the overhead of a function call to the plus will be small relative to the time to actually add the two vectors. So marking the operator+ inline is not likely to improve your overall run time.


Let the compiler to decide about optimization.

The keyword inline is misleading: the compiler can -in fact- always do what it needs, just like with the old auto (do you remenber those days?) and register.

It's modern meaning is "defined in header: discard if not used, merge if seen more times".


The compiler should inline smallish functions for you automatically in release builds. Much more important is to define a move constructor and move assignment. If your arrays are very large and you're doing multiple operations at the same time, you can also use expression classes to improve execution speed.

template <class left, class right>
struct AddExpr { 
    const left& _left;
    const right& _right;

    AddExpr(const left& Left, const right& Right)
    :_left(Left), _right(Right)
    {assert(left.count() == right.count());}
    int count() const {return _left.count();}
    int operator[](int index) const {return _left[i]+_right[i];}
};
class Array {
    int* data;
    int size;

    int count() const {return size;}
    Array& operator=(AddExpr expr) {
        for(int i=0; i<expr.count(); ++i)
           data[i] = expr[i];
};
AddExpr operator+(const Array& lhs, const Array& rhs) 
{return AddExpr<Array, Array>(lhs, rhs);}
AddExpr operator+(const Array& lhs, const Expr& rhs) 
{return AddExpr<Array, Expr>(lhs, rhs);}
AddExpr operator+(const Expr& lhs, const Array& rhs) 
{return AddExpr<Expr, Array>(lhs, rhs);}
AddExpr operator+(const Expr& lhs, const Expr& rhs) 
{return AddExpr<Expr, Expr>(lhs, rhs);}

int main() {
    Array a, b, c, d;
    Array c = (a+b) + (c+d);  //awesome on lines like this
}

This removes all the temporary objects, and greatly improves cache efficiency. But I've completely forgotten what this technique is called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜