Search code examples
javaperformancevariablesoptimizationencapsulation

Java: Which is faster? Local variables or accessing encapsulation?


I recently read a StackOverflow question that indicated, when accessing variables, it is faster to use the stack than the heap:

void f() {
    int x = 123; // <- located in stack
}

int x; // <- located in heap
void f() {
    x = 123  
}

However, I can't work it through my head which is faster in my example (since I assume they are both using the stack). I'm working on hitbox calculation and such, which uses alot of X-Y, width, height variables (up to 10-20 times for each) in the function.

Is it faster to use an object's get() method each time or set it to a local variable at the start of the function?

In code, is it faster to (or more efficient to):

void f() {
    doSomething(foo.getValue() + bar.getValue()); 
    doSomethingElse(foo.getValue(), bar.getValue());
    doAnotherThing(foo.getValue(), bar.getValue());
    // ... <- lot's of accessing (something.getValue());
}

or

void g() {
    int firstInt = foo.getValue();
    int secondInt = bar.getValue();

    doSomething(firstInt + secondInt);
    doSomethingElse(firstInt, secondInt);
    doAnotherThing(firstInt, secondInt);
    // ... <- lot's of accessing firstInt and secondInt
}

when foo and bar are MyObject's

public class MyObject {
    int x = 1;
    public int getValue() {
        return x;
    }
}

If they are about the same efficiency, how many times do I have to perform a .getValue() for it to become less efficient?

Thanks in advance!


Solution

  • JIT will change (optimize) your code on runtime, so this is not important in Java. One simple JIT optimization is method inlining.

    For further optimization read about Micro Benchmarking and look at this question How do I write a correct micro-benchmark in Java?