为什么在String#hashCode中有一个局部变量引用值数组?

时间:2016-05-25 07:38:22

标签: java

value引用复制到val变量的目的是什么,反对直接使用它?

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;    // private final char value[];

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

2 个答案:

答案 0 :(得分:0)

这是根据Martin Buchholz

进行的效果优化
  

复制到本地生成最小的   字节码

另见:
In ArrayBlockingQueue, why copy final member field into local final variable?

+----------------------+----------------------------+------------------------------+
| h = 31 * h + val[i]; | h = 31 * h + value[i];     | hash = 31 * hash + value[i]; |
+----------------------+----------------------------+------------------------------+
| LINENUMBER 1471 L7   | LINENUMBER 14 L6           | LINENUMBER 13 L4             |
| BIPUSH 31            | BIPUSH 31                  | ALOAD 0                      |
| ILOAD 1              | ILOAD 1                    | BIPUSH 31                    |
| IMUL                 | IMUL                       | ALOAD 0                      |
| ALOAD 2              | ALOAD 0                    | GETFIELD String.hash : I     |
| ILOAD 3              | GETFIELD String.value : [C | IMUL                         |
| CALOAD               | ILOAD 2                    | ALOAD 0                      |
| IADD                 | CALOAD                     | GETFIELD String.value : [C   |
| ISTORE 1             | IADD                       | ILOAD 1                      |
|                      | ISTORE 1                   | CALOAD                       |
|                      |                            | IADD                         |
|                      |                            | PUTFIELD String.hash : I     |
+----------------------+----------------------------+------------------------------+

答案 1 :(得分:-1)

这可能是为了表现。根据{{​​3}},访问局部变量(非常轻微)比访问实例变量更快。在Java库中,这种微优化当然是件好事。