Java:哪个更快?局部变量或访问封装? [英] Java: Which is faster? Local variables or accessing encapsulation?

查看:171
本文介绍了Java:哪个更快?局部变量或访问封装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了 StackOverflow问题,指出在访问变量时,它是使用堆栈的速度比堆快:

I recently read a StackOverflow question that indicated, when accessing variables, it is faster to use the stack than the heap:

void f() {
    int x = 123; // <- located in stack
}

int x; // <- located in heap
void f() {
    x = 123  
}

然而,我不能通过我的头脑来工作,这在我的例子中更快(因为我假设他们都在使用堆栈)。我正在研究hitbox计算等,它在函数中使用了很多X-Y,宽度,高度变量(每个最多10-20次)。

However, I can't work it through my head which is faster in my example (since I assume they are both using the stack). I'm working on hitbox calculation and such, which uses alot of X-Y, width, height variables (up to 10-20 times for each) in the function.

每次使用对象的 get()方法或将其设置为局部变量是否更快函数的开始?

Is it faster to use an object's get() method each time or set it to a local variable at the start of the function?

在代码中,它更快(或更有效):

In code, is it faster to (or more efficient to):

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 's

public class MyObject {
    int x = 1;
    public int getValue() {
        return x;
    }
}

如果效率大致相同,多少次我是否必须执行 .getValue()才能降低效率?

If they are about the same efficiency, how many times do I have to perform a .getValue() for it to become less efficient?

提前致谢!

推荐答案

JIT 将在运行时更改(优化)您的代码,因此这在Java中并不重要。一个简单的JIT优化是方法内联

JIT will change (optimize) your code on runtime, so this is not important in Java. One simple JIT optimization is method inlining.

如需进一步优化,请阅读 Micro Benchmarking 并查看此问题如何在Java中编写正确的微基准测试?

For further optimization read about Micro Benchmarking and look at this question How do I write a correct micro-benchmark in Java?

这篇关于Java:哪个更快?局部变量或访问封装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆