JDK代码中的优化 之 “avoid getfield opcode”

在查看String类源码时,常看到注释 /* avoid getfield opcode */

如 trim()方法

 1  public String trim() {
 2         int len = value.length;
 3         int st = 0;
 4         char[] val = value;    /* avoid getfield opcode */
 5 
 6         while ((st < len) && (val[st] <= ' ')) {
 7             st++;
 8         }
 9         while ((st < len) && (val[len - 1] <= ' ')) {
10             len--;
11         }
12         return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
13     }

 经查 getfield 为jvm 指令助记符, 指令码为0XB4,  功能为 获取指定类的实例域,并将其值压入栈顶

下面通过两段代码的字节码文件来比较一下:

代码1,

 1 public class Test {
 2     char[] arr = new char[100];
 3     public void test() {
 4         System.out.println(arr[0]);
 5         System.out.println(arr[1]);
 6         System.out.println(arr[2]);
 7     }
 8     public static void main(MyString[] args) {
 9         Test t = new Test();
10         t.test();
11     }
12 }
13 
14 
15  

 代码2:

 1 public class Test2 {
 2     char[] arr = new char[100];
 3     public void test() {
 4         char[] v1 = arr;
 5         System.out.println(v1[0]);
 6         System.out.println(v1[1]);
 7         System.out.println(v1[2]);
 8     }
 9     public static void main(MyString[] args) {
10         Test t = new Test();
11         t.test();
12     }
13 }
14 
15 
16  

 

注意到两个字节码文件中的getfield操作的次数,代码2只出现一次,即将arr 赋值给 v1, 而代码2中则在每次print时,均执行getfield操作。

总结:在一个方法中需要大量引用实例域变量的时候,使用方法中的局部变量代替引用可以减少getfield操作的次数,提高性能

原文地址:https://www.cnblogs.com/captains/p/5910089.html