Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve += operator performance

Tags:

c++

c++11

I am writing an application that must be very fast. I use Qt 5.5 with Qt Creator, the 64 bit MSVC2013 compiled version of Qt.

I used very sleepy CS to profile my application, and I saw that the function that took the most exclusive time was an operator+= overload (which is called, as you guess, a lot of times).

Here's the piece of code.

struct Coordinate
{
    float                   x;
    float                   y;

    Coordinate operator+=(const Coordinate &coord)
    {
        this->x += coord.x;
        this->y += coord.y;
        return (*this);
    }
};

I wondered if there were a way to improve performance of a function as simple as this one.

like image 449
Krapow Avatar asked Nov 30 '22 09:11

Krapow


2 Answers

operator+= is not quite defined the way you did. Rather, it should be:

Coordinate& operator+=(const Coordinate &coord);

Note the return value of a reference.

This also has the benefit of not creating another copy.

like image 98
Ami Tavory Avatar answered Dec 27 '22 09:12

Ami Tavory


Check if you are profiling Release configurion and compiler optimizations are enabled. Such calls should be inlined by any decent compiler.

like image 32
dewaffled Avatar answered Dec 27 '22 08:12

dewaffled