mercredi 26 août 2015

Why is a placement new much faster than a direct assignment?

I recently figured out that using a placement new is faster than doing 16 assignments:
Consider the following piece of code (c++11):

class Matrix
{
public:
    double data[16];

    Matrix() : data{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
    {
    };

    void Identity1()
    {
        new (this) Matrix();
    };

    void Identity2()
    {
        data[0]  = 1.0; data[1]  = 0.0; data[2]  = 0.0; data[3]  = 0.0;
        data[4]  = 0.0; data[5]  = 1.0; data[6]  = 0.0; data[7]  = 0.0;
        data[8]  = 0.0; data[9]  = 0.0; data[10] = 1.0; data[11] = 0.0;
        data[12] = 0.0; data[13] = 0.0; data[14] = 0.0; data[15] = 1.0;
    };
};

Usage:

Matrix m;
//modify m.data

m.Identity1(); //~25 times faster
m.Identity2();

On my machine Identity1() is about 25 times faster than the second function. And now im curious why there is such a big difference?

I also tried a third one:

void Identity3()
{
    memset(data, 0, sizeof(double) * 16);
    data[0] = 1.0;
    data[5] = 1.0;
    data[10] = 1.0;
    data[15] = 1.0;
};

But this is even slower than Identity2() and i can't imagine why.

Edit: Compiled with g++ -O3

Aucun commentaire:

Enregistrer un commentaire