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

后端 未结 10 2313
无人及你
无人及你 2020-12-06 09:26

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

相关标签:
10条回答
  • 2020-12-06 09:36

    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.

    0 讨论(0)
  • 2020-12-06 09:39

    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:

    0 讨论(0)
  • 2020-12-06 09:42

    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.

    0 讨论(0)
  • 2020-12-06 09:43

    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.

    0 讨论(0)
  • 2020-12-06 09:44

    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.

    0 讨论(0)
  • 2020-12-06 09:47

    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.

    0 讨论(0)
提交回复
热议问题