【发布时间】:2013-12-23 19:34:30
【问题描述】:
我最近读到一个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() 才能使其效率降低?
提前致谢!
【问题讨论】:
-
请不要尝试像这样优化您的代码。首先让它工作......一般来说,这些微优化是没有意义的。您需要对实际代码中的更改进行基准测试,以确定它们对您的用例是否重要。
-
为什么会有不同?请谷歌搜索“过早优化”。
-
如果您想知道效率的转折点在哪里,您需要自己进行适当的微基准测试。答案因您的硬件和软件而异。
-
我确信我不是唯一一个不知道基准测试存在的人。我的代码确实有效,所以我只是想问一下它是否有影响,如果有人知道,有什么不同。
-
我不相信你链接的帖子。正确测量,您肯定会发现没有区别......
标签: java performance variables optimization encapsulation