javavariablesoptimization

Performance enhancements through use of public variables?


In regards to Java, I'm very accustomed to declaring all of my variables as private and generating public getters and setters to hold true to common convention.

I find it curious, though: in relation to getters and setters with no functionality outside of assigning and returning the requested value, is there no performance hit for calling methods like:

String getValue() {
    return value;
}

instead of:

classInstance.value;

Does the compiler do something here to help keep the function call from adding an extra cycle? If not, then doesn't this theoretical hit snowball into a large hit in more robust applications?

Edit:: For clarification, this question is not asking why you should or shouldn't use accessor methods, the question is whether or not you take a performance hit by using accessors.


Solution

  • Does the compiler do something here to help keep the function call from adding an extra cycle?

    Yes.

    A Hotspot JIT compiler will inline short methods, and a simple getter or setter is short enough to allow that. Inlining the method body gets rid of the overheads of the parameter assembly and the method call, and allows further local optimization in the context of the calling method.

    The net result is that using getters and setters is not a performance hit on a modern JVM(tm)

    (Some early Android compilers didn't do this, but this has been rectified.)