为什么static / member变量比局部变量慢? [英] Why static/member variable are slower than local variable?

查看:131
本文介绍了为什么static / member变量比局部变量慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过这个帖子:如果与条件相比的速度

我自己上课检查速度

public class Question {
static long startTime;
static long elapsedTime;

static String mStatic;
private String mPublic;

public static void main(String[] args) {
    Question q = new Question();
    q.executeGlobal();
    q.executeStatic();
    q.executeLocal();
}

public void executeLocal() {
    String mLocal;
    startTime = System.nanoTime();
    for (int i = 0; i < 1000000000; i++) {
        mLocal = "";
    }
    elapsedTime = System.nanoTime() - startTime;
    System.out.println("Type Local: " + elapsedTime + " ns");

}

public void executeGlobal() {
    startTime = System.nanoTime();
    for (int i = 0; i < 1000000000; i++) {
        mPublic = "";
    }
    elapsedTime = System.nanoTime() - startTime;
    System.out.println("Type Global: " + elapsedTime + " ns");

}

public void executeStatic() {
    startTime = System.nanoTime();
    for (int i = 0; i < 1000000000; i++) {
        mStatic = "";
    }
    elapsedTime = System.nanoTime() - startTime;
    System.out.println("Type Static: " + elapsedTime + " ns");
}

}

结果:

Type Global: 45693028 ns
Type Static: 43853723 ns
Type Local: 2057505 ns

在答案中@Rod_algonquin回答是因为 getstatic / putstatic 静态变量的字节码和 getfield / putfield 成员变量的字节码,它通过位移和一些加法来计算。

In the answer @Rod_algonquin answered that it is because of the getstatic/putstatic bytecode for static variable and getfield/putfield bytecode for the member variable, that it is calculating through bit-shifting and some addition.

起初我认为只有对象会导致这种情况,但在尝试引用原语时,结果是相同的本地变量仍然是更快

At first I thought that only Objects causes this, but upon trying to reference primitive the result is the same local variable is still faster.

为什么该局部变量更快?除了字节码解释。

Why is that local variable is faster? except the bytecode explanation.

推荐答案

你是运行时优化的受害者: - )

youre a victim of runtime optimization :-)

如果您稍微更改一下代码:

if you change your code a little:

Question q = new Question();
for (int i=0; i<2; i++) {
    q.executeGlobal();
    q.executeStatic();
    q.executeLocal();
}

你得到这个:

Type Global: 38331943 ns
Type Static: 57761889 ns
Type Local: 3010189 ns
Type Global: 46249688 ns
Type Static: 52745009 ns
Type Local: 0 ns

运行时很快就会发生您的局部变量不断被分配,但永远不会被读取(或使用),并优化整个循环。

what happens is that pretty soon the runtime realizes that your local variable keeps getting assigned, but never gets read (or used), and optimizes out the whole loop.

类实例字段和静态字段之间的差异,它们都在堆上,但静态字段在所有对象实例之间共享,因此有一个额外的间接级别

as for the difference between class instance fields and static fields, theyre both on the heap, but the static fields are shared across all object instances, so there's an extra level of indirection

这篇关于为什么static / member变量比局部变量慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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