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

后端 未结 10 2343
无人及你
无人及你 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: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; }
    }
    

提交回复
热议问题