vendredi 10 juillet 2020

Performance implications of inline function using this pointer versus using two arguments

Background

I am studying Math related to Game Engines from the book Foundations of Game Engine Development, Volume 1: Mathematics.
The implementation of operator overloads seemed different than the way I would have done it had I not been reading this book and looking at its examples. I wanted to see if the way the author coded it up had performance implications. Searching for the answer to this question was difficult and I could only find other questions about inlining that had nothing to do with comparing these specific styles of declaring operator overloads.

The Example

Vec3.h Version 1

class Vec3
{
public:

    float x;
    float y;
    float z;

    Vec3(float x, float y, float z);

    inline Vec3 operator+(const Vec3& rval) const
    {
        return Vec3(this->x+rval.x, this->y+rval.y, this->z+rval.z);
    }
};

vs

Vec3.h Version 2

class Vec3
{
public:
    float x;
    float y;
    float z;
    Vec3(float x, float y, float z);

};
inline Vec3 operator+(const Vec3& lval, const Vec3& rval)
{
    return Vec3(lval.x+rval.x, lval.y+rval.y, lval.z+rval.z);
}

The Question

Version 1 is how I would have implemented the operator+ overload. It seems like the C++ way, making the operator a method of the class.

However, I see throughout the book that the author continues to use version 2 whenever declaring overloads. He declares them outside of the class definition and uses 2 arguments (lval and rval) rather than the implicit this(lval) and right hand argument(rval)

If you try to implement both, understandably there is a compiler error saying it's ambiguous. Which is exactly why I am here to ask this question. To me, it's equivalent and I would rather not have a function sitting in global space, so I would implement version 1.

However, I figured there might be a performance reason for implementing version 2. Maybe inlining is easier for the compiler, or it executes faster for some arcane reason that the author does not mention.

Another idea I had is that perhaps inline is actually functioning more like "static" in this case. I have read elsewhere that inline is pretty much ignored by the compiler anyways because it's going to try to inline it anyway.

When doing

Vec3 v1(1,2,3);
Vec3 v2(1,2,3);
Vec3 v3 = v2-v1;

which performs better? Or, is this just more of a preference thing? Additionally, would it behave differently based on the C++ version? (tagged C++11, 14, and 17 for that reason)

Aucun commentaire:

Enregistrer un commentaire