我最近读了一篇 StackOverflow question这表明,在访问变量时,使用堆栈比使用堆更快:
void f() {
int x = 123; // <- located in stack
}
int x; // <- located in heap
void f() {
x = 123
}
但是,我无法通过我的头脑来解决这个问题,这在我的示例中更快(因为我假设他们都在使用堆栈)。我正在研究 hitbox 计算等,它在函数中使用了很多 X-Y、宽度、高度变量(每个变量最多 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());
}
或
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
}
当foo
和bar
是MyObject
的
public class MyObject {
int x = 1;
public int getValue() {
return x;
}
}
如果它们的效率大致相同,我必须执行多少次 .getValue()
才能使其效率降低?
提前致谢!
最佳答案
JIT将在运行时更改(优化)您的代码,因此这在 Java 中并不重要。一种简单的 JIT 优化是 method inlining .
要进一步优化,请阅读 Micro Benchmarking看看这个问题How do I write a correct micro-benchmark in Java?
关于Java:哪个更快?局部变量还是访问封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750020/