Question

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!

Was it helpful?

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?

OTHER TIPS

If you do use local variables, you may tell the compiler that the value will not be changed final int x = ...;, turning it in some kind of local constant.

Reassigning values (recycling objects and such) may help reduce garbage collection (GC).

Write some extreme stress test, if possible a visual one too, let it run for a long time and measure real performance, perceived performance. A better faster time is not always better, sometimes it may be a bit slower but a bit smoother across the execution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top