字符串不变性允许缓存哈希码值

时间:2022-03-02 16:50:34

Among the many reasons to why Strings are immutable, one of the reasons is cited as

在为什么字符串不可变的众多原因中,其中一个原因被引用为

String immutability allows hashcode value to be cached.

字符串不变性允许缓存哈希码值。

I did not really understand this. What is meant by caching hashcode values? Where are these values cached? Even if Strings would have been mutable, this cached hashcode value could always be updated as required; so what's the big deal?

我真的不明白这一点。缓存哈希码值是什么意思?这些值缓存在哪里?即使字符串是可变的,也可以根据需要更新此缓存的哈希码值;那有什么大不了的?

1 个解决方案

#1


5  

What is meant by caching hashcode values? Where are these values cached?

缓存哈希码值是什么意思?这些值缓存在哪里?

After the hash code is calculated, it is stored in a variable in String.
Looking at the source of String makes this clearer:

在计算哈希码之后,它将存储在String中的变量中。查看String的来源使这更清楚:

public final class String implements ... {
    ...
    /** Cache the hash code for the string */
    private int hash; // Default to 0

    ...

    public int hashCode() {
        int h = hash;
        if (h == 0 && ...) {
            ...
            hash = h;
        }
        return h;
    }

    ...
}

Even if Strings would have been mutable, this cached hashcode value could always be updated as required

即使字符串是可变的,也可以根据需要随时更新此缓存的哈希码值

True. But it would have to be recalculated / reset in every modification function. While this is possible, it's not good design.

真正。但是必须在每个修改函数中重新计算/重置它。虽然这是可能的,但这不是好设计。

All in all, the reason probably would've been better if it were as follows:

总而言之,如果如下,原因可能会更好:

String immutability makes it easier to cache the hashcode value.

字符串不变性使得缓存哈希码值更容易。

#1


5  

What is meant by caching hashcode values? Where are these values cached?

缓存哈希码值是什么意思?这些值缓存在哪里?

After the hash code is calculated, it is stored in a variable in String.
Looking at the source of String makes this clearer:

在计算哈希码之后,它将存储在String中的变量中。查看String的来源使这更清楚:

public final class String implements ... {
    ...
    /** Cache the hash code for the string */
    private int hash; // Default to 0

    ...

    public int hashCode() {
        int h = hash;
        if (h == 0 && ...) {
            ...
            hash = h;
        }
        return h;
    }

    ...
}

Even if Strings would have been mutable, this cached hashcode value could always be updated as required

即使字符串是可变的,也可以根据需要随时更新此缓存的哈希码值

True. But it would have to be recalculated / reset in every modification function. While this is possible, it's not good design.

真正。但是必须在每个修改函数中重新计算/重置它。虽然这是可能的,但这不是好设计。

All in all, the reason probably would've been better if it were as follows:

总而言之,如果如下,原因可能会更好:

String immutability makes it easier to cache the hashcode value.

字符串不变性使得缓存哈希码值更容易。