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

后端 未结 10 2314
无人及你
无人及你 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:49

    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.

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

    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.

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

    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; }
    }
    
    0 讨论(0)
  • 2020-12-06 09:56

    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.

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