Is there any performance hit for simple if?

For example, I have a class

class Point
{
public:
    float operator[](int i) const
    {
       if (i == 0) return m_x; // simple ifs, performance reduction??
       if (i == 1) return m_y;
       return m_z;
    }

private:
    float m_x;
    float m_y;
    float m_z;
};

Is there any performance degradation compared to accessing an item std::array<float, 3>? If so, how to remove it. I want to use the x, y, z fields except an array.

+4
source share
4 answers

Is there a decrease in performance?

I suppose you mean, "compared to doing an array search."

, () - ( , ), . , - , .

, . x, y, z, .

ifs, .

, , :

class Point 
{
public:
   [...]

   float & m_x() {return m_array[0];}
   float & m_y() {return m_array[1];}
   float & m_z() {return m_array[2];}

private:
   float m_array[3];
};

[...]

myPoint.m_x() = 5;
myPoint.m_y() = myPoint.m_x() + myPoint.m_z();
[etc]
+3

. getter .

class Point
{
public:
    float operator[](int i)
    {
       return coords[i]
    }
    float getX() {
        return coords[0];
    }
    float getY() {
        return coords[1];
    }
    float getZ() {
        return coords[2];
    }
    float setX(float val) {
        return coords[0] = val;
    }
    float setY(float val) {
        return coords[1] = val;
    }
    float setZ(float val) {
        return coords[2] = val;
    }

private:
    float coords[3];
};
+1

:

    const int max = 1000000000;
    int sum1 = 0;
    int sum2 = 0;
    int t = time(NULL);
    int n;
    for (int i = 0; i < max; ++i) 
    {
        n = (rand() % 3) + 1;
        sum1 += n;
    }
    int t2 = time(NULL);
    cout << t2 - t << endl;

    for (int i = 0; i < max; ++i)
    {
        n = (rand() % 3) + 1;
        if (n == 1)
            sum2 += 1;
        else if (n == 2)
            sum2 += 2;
        else
            sum2 += 3;
    }
    int t3 = time(NULL);
    cout << t3 - t2 << endl;

V++ Visual Studio 2015 . , , 30 . - , , , , . 1 000 000 000 , , . , , , , .

EDIT: , , . , ( ), 43 46 - .

0

, . , :

float operator[](int i) {
    return *(&m_x + i);
}

, .

, if. , , ( 0 2).

, - . , , , , , , , - , .

-3

All Articles