Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c++

d

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.

like image 305
alvatar Avatar asked Jul 10 '09 14:07

alvatar


People also ask

Do getters and setters speed up compilation?

Getters and setters can speed up compilation. Getters and setters provide encapsulation of behavior. Getters and setters provide a debugging point for when a property changes at runtime.

Are getters and setters bad Java?

Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.

What is advantage of getter and setter in Java?

The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement. 2.

Should you always use getters and setters?

Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will. Typical example, consider having a dateOfBirth parameter.


10 Answers

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.

like image 99
jalf Avatar answered Oct 04 '22 15:10

jalf


In D, all methods of classes, but not structs, are virtual by default. You can make a method non-virtual by making either the method or the whole class final. Also, D has property syntax that allows you to make something a public field, and then change it to a getter/setter later without breaking source-level compatibility. Therefore, in D I would recommend just using public fields unless you have a good reason to do otherwise. If you want to use trivial getters/setters for some reason such as only having a getter and making the variable read-only from outside the class, make them final.


Edit: For example, the lines:

S s;
s.foo = s.bar + 1;

will work for both

struct S
{
     int foo;
     int bar;
}

and

struct S
{
     void foo(int) { ... }
     int bar() { ... return something; }
}
like image 27
dsimcha Avatar answered Oct 04 '22 15:10

dsimcha


I tried in Java: the same thing with and without getter and setter. The result: there is no significant difference between the execution time of the two versions. Here' s the code:

class Person
{
    public int age;
    String name;
    public Person(String name,int age)
    {
        this.name=name;
        this.age=age;   
    }

}
class GetSetPerson
{
    private int age;
    String name;
    public GetSetPerson(String name,int age)
    {
        this.name=name;
        this.age=age;   
    }
    public void setAge(int newage)
    {
        age=newage;
    }
    public int getAge()
    {
    return age; 
    }
}
class Proba
{
//Math.hypot kb 10-szer lassabb, mint a Math.sqrt(x*xy*y)!!!

public static void main(String args[])
{
long startTime, endTime, time;
int i;int agevar;
//Person p1=new Person("Bob",21);
GetSetPerson p1=new GetSetPerson("Bob",21);
startTime=System.nanoTime();
/*
for (i=0;i<1000000000;i++)
     {
     p1.age++;

     }

*/    
for (i=0;i<1000000000;i++)
     {
     agevar=p1.getAge();
     agevar++;
     p1.setAge(agevar);
     }

endTime=System.nanoTime();
time=endTime-startTime;
System.out.println(""+time);
System.out.println(p1.name+"'s age now  is "+p1.getAge());
}

}

I know, at the end Bob is a bit older than me, but for this, it should be okay.

like image 28
Arpad Kosa Avatar answered Oct 04 '22 16:10

Arpad Kosa


I had exactly the same question once.

To answere it I programmed two small Programs:

The first:

#include <iostream>

class Test
{
     int a;
};

int main()
{
    Test var;

    var.a = 4;
    std::cout << var.a << std::endl;
    return 0;
}

The second:

#include <iostream>

class Test
{
     int a;
     int getA() { return a; }
     void setA(int a_) { a=a_; }
};

int main()
{
    Test var;

    var.setA(4);
    std::cout << var.getA() << std::endl;
    return 0;
}

I compiled them to assembler, with -O3 (fully optimized) and compared the two files. They were identical. Without optimization they were different.

This was under g++. So, to answere your question: Compilers easily optimize getters and setters out.

like image 43
Marenz Avatar answered Oct 04 '22 15:10

Marenz


Any JVM (or compiler) worth its salt needs to support inlining. In C++, the compiler inlines the getters and setters. In Java, the JVM inlines them at runtime after they have been called "enough" times. I don't know about D.

like image 39
notnoop Avatar answered Oct 04 '22 16:10

notnoop


Depending on the expected evolution of your class, get/setters may clutter your code vs. give you the flexibility to extend your implementation without affecting the client code.

Often I encounter classes that are used as 'data containers', which have both getter and setter for each member. That's nonsense. If you don't expect to need some 'special' functionality to be triggered when getting or setting a member, don't write it.

Given the speed of the machine, the effort of writing the extra abstraction will cost your clients more money.

Most compilers can optimize trivial getters/setters, but as soon as you declare them virtual (in C++), you pay an extra lookup - often worth the effort.

like image 29
xtofl Avatar answered Oct 04 '22 17:10

xtofl


A getter would be required for certain members in some cases. However providing a getter and setter for each data member of a class is not a good practice. Doing that would be complicating the class's interface. Also setters would bring in resource ownership issues if not handled properly.

like image 38
Modicom Avatar answered Oct 04 '22 17:10

Modicom


Quoting from here Regarding the D Programming Langiage

I think DMD is currently unable to de-virtualize virtual getters and setters. Virtual calls are a bit slower by itself, but they also don't allow inlining, so successive standard optimizations can't be done. So if such accesses to the attribute is a virtual call and this happens in a "hot" part of the code, then it may slow down your code significantly. (if it happens in non-hot parts of the code it has usually no effects. That's why Java Hot Spot doesn't need optimize all your code to produce a very fast program anyway).

I have encouraged Frits van Bommel to improve the devirtualization capabilities of LDC:

Now LDC is able to do that in few very simple situations, but most times the situation is unchanged compared to DMD. Eventually LLVM will improve, so this situation can improve by itself. But the front-end too may do something about this.

Here is some documentation about this topic, some older, some more modern:

like image 40
BCS Avatar answered Oct 04 '22 15:10

BCS


In C++, when a compiler's optimizations are enabled then getters and setters may be 'inlined': i.e., be implemented using the same machine instructions as there would be for direct access to the underlying member data.

like image 44
ChrisW Avatar answered Oct 04 '22 15:10

ChrisW


I'll echo Xtofl.

Getters and setters are one of those things that are sometimes useful, but you get these doctrinaire people who somehow leap from "has proven useful in some cases" to "must be used all the time and if you don't use it you are a heretic who should be killed".

If you have side effects to a get or set, by all means use a getter or setter.

But if not, writing getters and setters just clutters up the code. There's a small performance penalty. In Java, if it's only executed a few times, the perforance penalty shouldn't matter, and if it's executed frequently, it should be inlined so the penalty is mitigated. So I'd worry more about making the code harder to read.

And don't for a minute buy the argument that this eliminates the problem of global data. Global data is bad and should be avoided. But declaring a member field private and then creating public getters and setters for does nothing to solve the problem.

like image 1
Jay Avatar answered Oct 04 '22 16:10

Jay