gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:28:27 29 4
gpt4 key购买 nike

复制 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;
}

最佳答案

这是根据 Martin Buchholz 进行的性能优化

copying to locals produces the smallest bytecode

另见:
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 |
+----------------------+----------------------------+------------------------------+

关于java - 为什么在String#hashCode中有一个局部变量引用值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430665/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com