美文网首页
为什么有些Java 类方法中要cache类变量

为什么有些Java 类方法中要cache类变量

作者: yangweigbh | 来源:发表于2018-01-18 20:00 被阅读154次

比如以下一段java代码:

private void performTraversals() {
    // cache mView since it is used so much below...
    final View host = mView;

    ......
}

为什么要这么写呢?

下面用一段测试程序的bytecode来解释一下(以下bytecode是基于JVM的,不是基于art的):

public class TestLocal {
    private int i = 1;

    public void foo() {
        long before = System.currentTimeMillis();
        for (int j = 0; j < 10000; j++) {
            System.out.print(i);
        }

        System.out.println();
        System.out.println("TestLocal result: " + (System.currentTimeMillis() - before));
    }

    public static void main(String[] args) {
        new TestLocal().foo();
        new TestLocal2().foo();
    }
}


class TestLocal2 {
    private int i = 1;

    public void foo() {
        int k = i;
        long before = System.currentTimeMillis();
        for (int j = 0; j < 10000; j++) {
            System.out.print(k);
        }

        System.out.println();
        System.out.println("TestLocal2 result: " + (System.currentTimeMillis() - before));
    }
}

TestLocalfoo方法,直接读取类变量,对应的字节码是

        13: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
        16: aload_0
        17: getfield      #2                  // Field i:I
        20: invokevirtual #5                  // Method java/io/PrintStream.print:(I)V

每次都需要将this push到operand stack中,然后去堆里找对应的field。

TestLocal2foo方法,是将类变量的值存储在当前Frame的local variable中。然后每次调用只要从local variable中取用。

         0: aload_0
         1: getfield      #2                  // Field i:I
         4: istore_1
         .......
        20: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
        23: iload_1
        24: invokevirtual #5                  // Method java/io/PrintStream.print:(I)V

运行时间对比:

TestLocal result: 145 ms
TestLocal2 result: 128 ms

所以将类变量缓存到方法的local variable中还是能提升运行速度的,尤其是如果类变量会被经常访问。

相关文章

  • 为什么有些Java 类方法中要cache类变量

    比如以下一段java代码: 为什么要这么写呢? 下面用一段测试程序的bytecode来解释一下(以下bytecod...

  • Java初始化顺序

    Java初始化顺序:①类变量、类方法>②(父类代码)>③实例变量>④构造器当一个类要实例化时,static变量和方...

  • final关键字的理解

    在Java中,final关键字可以用来修饰类、方法和变量(类变量和实例变量以及局部变量),在Java中做到了无孔不...

  • 实例讲解java中的变量类型

    实例讲解java中的变量类型 首先Java语言支持的变量类型有三类,分别是: 类变量:独立于方法之外的变量,用 s...

  • Kotlin基础--静态方法、静态变量和常量

    在Java中我们通常会使用静态变量和静态方法作为工具类。 那如何在Kotlin中类名直接调用类的方法和变量呢?先来...

  • Java基础---变量、构造器、构造方法

    Java语言支持的变量类型有: 类变量:独立于方法之外的变量,用 static 修饰。 重点:在类中以static...

  • iOS消息转发机制

    oc调用方法流程 1.先去自己cache中查找,再去类的方法列表中查找 2.再去父类的cache中和方法列表中 /...

  • final,finally和finalize的区别

    在java中,final可以用来修饰类,方法和变量(成员变量或局部变量)。下面将对其详细介绍。 1.1 修饰类 当...

  • 1、final关键字

    1. 作用 final在Java中可以声明成员变量、方法、方法参数、类以及本地变量。 1.1 final变量 凡是...

  • java中的全局变量、局部变量与static

    java中的变量类型有: 类变量:独立于方法之外的变量,用 static 修饰。 实例变量:独立于方法之外的变量,...

网友评论

      本文标题:为什么有些Java 类方法中要cache类变量

      本文链接:https://www.haomeiwen.com/subject/lpbwoxtx.html