我最近阅读了一个StackOverflow的问题,它表明,在访问变量时,使用栈比使用堆更快:
void f() {
int x = 123; // <- located in stack
}
int x; // <- located in heap
void f() {
x = 123
}
然而,我无法确定在我的例子中哪个更快(因为我假设它们都使用堆栈)。我正在处理碰撞检测等内容,其中函数中使用了许多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()
才会变得不太高效?先行致谢!