c++ - Is there any performance reduction for simple if? -


for example, have 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 performance reduction compare access element of std::array<float, 3>? if so, how can remove it. want use fields x, y, z other array.

is there performance reduction?

i assume mean, "compared doing array lookup".

if so, answer (potentially) yes -- branching operation can potentially cause pipeline stall (if cpu mispredicts branch taken), make things slower. cpu branch prediction pretty these days, might not issue in real life--it depend lot on usage patterns of program calling code.

if so, how can remove it. want use fields x, y, z other array.

you can remove ifs using three-item array instead of 3 separate items.

if don't accessing items array, can add accessor methods make array separate items again:

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] 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -