lundi 18 février 2019

Performance issues when using const auto& x and auto x to get the return value

Let's look at this code:

#include <iostream>

class X
{
    double m_a, m_b, m_c;
public:
    X(double a = 0.0, double b = 0.0, double c = 0.0f)
        : m_a(a)
        , m_b(b)
        , m_c(c)
    {}
};

class Y
{
public:
    X m_x;
    Y() 
        : m_x(X(1.0, 2.0, 3.0))
    {}

    const X& get_x() { return m_x; }
};

int main()
{
    for (unsigned i = 0; i < 1000000000; ++i)
    {
        Y y;
        const auto& x = y.get_x(); // gives 16.5 - 17.5 sec runtime
        //auto x = y.get_x(); //  uncommenting this makes it 10.6 - 12.2 sec !
    }
}

As you see runtime results in the comments section from the code above means that that copying return value in the object x might be perform faster than using const reference for it - why ?

  1. Is this due to additional overhead added when dealing with references ?
  2. What caching mechanism (if they ever) worked here for the case with auto x = ... to get better performance ?

Used g++ 6.2 to compile the code using this command:

g++ -std=c++14 test.cpp -o test && time ./test

Aucun commentaire:

Enregistrer un commentaire