Java String中的hashCode实现

Kon*_*gin 7 java

只是好奇,在String的hashCode实现中,在hashCode实现中创建额外引用的原因是什么(v 1.8.0_65):

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

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

考虑到value最终只在构造函数中创建(即线程安全)为什么我们需要变量val []引用?

即,这将工作:

public int hashCode() {
    if (hash == 0 && value.length > 0) {
        int h = 0;
        for (int i = 0; i < value.length; i++) {
            h = 31 * h + value[i];
        }
        hash = h;
    }
    return hash;
}
Run Code Online (Sandbox Code Playgroud)

除了将值从堆复制到堆栈以加快速度之外,它还涉及@zapl在注释中描述的竞争条件.在他发表评论之前,这对我来说并不明显.

Con*_*Del 1

看起来意图是将hash句柄value显式地放在堆栈上