Java:哪个更快?局部变量或访问封装?

sni*_*10m 3 java variables optimization performance encapsulation

我最近读了一个StackOverflow问题,表明在访问变量时,使用堆栈比堆更快:

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

int x; // <- located in heap
void f() {
    x = 123  
}
Run Code Online (Sandbox Code Playgroud)

但是,我无法通过我的头脑工作,这在我的例子中更快(因为我假设他们都在使用堆栈).我正在研究hitbox计算等,它在函数中使用了很多XY,宽度,高度变量(每个变量最多10-20次).

get()每次使用对象的方法或在函数开头将其设置为局部变量是否更快?

在代码中,它更快(或更高效):

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

要么

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
}
Run Code Online (Sandbox Code Playgroud)

foobarMyObject

public class MyObject {
    int x = 1;
    public int getValue() {
        return x;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果它们的效率大致相同,那么我必须执行多少次才能.getValue()降低效率?

提前致谢!

Mar*_*szS 11

JIT将在运行时更改(优化)您的代码,因此这在Java中并不重要.一个简单的JIT优化是方法内联.

有关Micro Benchmarking的进一步优化,请阅读此问题如何在Java中编写正确的微基准测试?