简体   繁体   中英

Improve += operator performance

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM