Java:哪个更快? 局部变量或访问封装?
我最近读了一个StackOverflow问题 ,表明在访问变量时,使用堆栈比堆更快:
void f() { int x = 123; // <- located in stack } int x; // <- located in heap void f() { x = 123 }
但是,我无法通过我的头脑工作,这在我的例子中更快(因为我假设他们都在使用堆栈)。 我正在研究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()); }
要么
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优化是方法内联 。
有关Micro Benchmarking的进一步优化,请阅读此问题如何在Java中编写正确的微基准测试?
如果你确实使用局部变量,你可以告诉编译器该值不会被改变final int x = ...;
把它变成某种局部常数。
重新分配值(回收对象等)可能有助于减少垃圾收集(GC)。
写一些极端压力测试,如果可能的话也是一个视觉测试,让它运行很长时间并测量真实性能,感知性能。 更快更好的时间并不总是更好,有时它可能会慢一点但在执行过程中会更平滑。