Do getters and setters impact performance in C++/D/Java?

alvatar picture alvatar · Jul 10, 2009 · Viewed 13k times · Source

This is a rather old topic: Are setters and getters good or evil?

My question here is: do compilers in C++ / D / Java inline the getters and setter?

To which extent do the getters/setters impact performance (function call, stack frame) compared to a direct field access. Besides all the other reasons for using them, I would like to know whether they are supposed to affect the performance besides being a good OOP practice.

Answer

jalf picture jalf · Jul 10, 2009

It depends. There is no universal answer that is always going to be true.

In Java, the JIT compiler will probably inline it sooner or later. As far as I know, the JVM JIT compiler only optimizes heavily used code, so you could see the function call overhead initially, until the getter/setter has been called sufficiently often.

In C++, it will almost certainly be inlined (assuming optimizations are enabled). However, there is one case where it probably won't be:

// foo.h
class Foo {
private:
  int bar_;

public:
  int bar(); // getter
};

// foo.cpp
#include "foo.h"

int Foo::bar(){
  return bar_;
}

If the definition of the function is not visible to users of the class (which will include foo.h, but won't see foo.cpp), then the compiler may not be able to inline the function call.

MSVC should be able to inline it if link-time code generation is enabled as an optimization. I don't know how GCC handles the issue.

By extension, this also means that if the getter is defined in a different .dll/.so, the call can not be inlined.

In any case, I don't think trivial get/setters are necessarily "good OOP practice", or that there are "all the other reasons for using them". A lot of people consider trivial get/setters to 1) be a sign of bad design, and 2) be a waste of typing.

Personally, it's not something I get worked up about either way. To me, for something to qualify as "good OOP practice", it has to have some quantifiable positive effects. Trivial get/setters have some marginal advantages, and some just as insignificant disadvantages. As such, I don't think they're a good or bad practice. They're just something you can do if you really want to.