Getters and Setters. Is there performance overhead?

sgtHale picture sgtHale · Dec 13, 2012 · Viewed 10.7k times · Source

I have a Particle System Engine in my C++ project and the particles themselves are just structs of variables with no functions. Currently, each particle (Particle) is updated from its parent class (ParticleSystem) by having its variables accessed directly. E.g.

particle.x += particle.vx;

I am however, debating using getters and setters like this:

particle.setX( particle.getX()+particle.getVX() );

My question is: Is there any performance overhead from calling getters and setters as opposed to just straight up data access?

After all, I do have many many particles to update through...

Answer

OmnipotentEntity picture OmnipotentEntity · Dec 13, 2012

Setters and getters have a performance overhead when not optimized out. They are almost always optimized out on compilers that do link time optimization. And on compilers that do not, if they have knowledge of the function body (ie not just a prototype) it will be optimized out.

However, you use getters and setters are there because you might want getting or setting that variable to have additional side effects. Like changing the position of an object also changes the position of nearby objects in a physics simulation or some such.

Finally, the overhead of a getter and setter operation, within the context of optimized code, is very small, not worth worrying about unless the code is hot. And if it's hot, it's SO EASY to just move the getter or setter to the header file and inline it.

So to sum up, getters and setters are well worth the minor or non-existent overhead, as it allows you to specify very specifically what can and cannot happen with your object, and it also allows you to marshal any changes.