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

标签 java performance variables optimization encapsulation

我最近读了一篇 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
}

foobarMyObject

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/

相关文章:

performance - 为什么我的欧拉计划第 12 题算法这么慢?

c# - 避免在 foreach 循环中等待

javascript - 第 n 个 child 的变量

javascript - 在 Ruby 中动态命名数组/哈希

javascript - 为变量内的函数设置 boolean 值

java - 如何获取 Unicode 字符的代码?

java - Oracle 从其他列计算结果中更新列

java - 神经网络没有主动响应已学习的内容

强制转换时的 Java 编译时错误

performance - Flutter - 缓慢的 gradle 构建