java - Guava ImmutableMap 中的性能警告

标签 java guava

在 Guava 的 ImmutableMap 的 javadocs 中说:

Performance notes: unlike HashMap, ImmutableMap is not optimized for element types that have slow Object.equals(java.lang.Object) or Object.hashCode() implementations. You can get better performance by having your element type cache its own hash codes, and by making use of the cached values to short-circuit a slow equals algorithm.

所以我的第一个问题是我如何知道我的元素是否有缓慢的 .equals 或 .hashCode 实现?在我的特定实例中,我使用 java Enum 作为我的 key ,因此它具有 .equals 和 .hashCode 的高效默认实现,对吗? (我假设这些值的实现是无关紧要的,只要您不使用值的值访问 map 。)

我的第二个问题是“让你的元素类型缓存它自己的哈希码”到底是什么意思!谷歌搜索我似乎无法找到你如何做到这一点的例子。我想也许这意味着您最终会在哈希码中得到哈希码?所以我进入哈希码桶,然后 .equals 方法在其中使用第二组哈希码?

最佳答案

I'm using a java Enum as my key, so that has an efficient default implementation of .equals and .hashCode, right?

equals 或 hashcode 都没有被覆盖,因此它几乎不会更快(即 equals 返回 this == other)。

My second question is what does "having your element type cache its own hash codes" even mean!

您可以使用类似下面的代码来避免多次计算 - 如果您这样做,您需要确保:

  • 哈希码是不变的(即在实例的整个生命周期中不能改变)
  • 您的 hashcode 方法是线程安全的(这可以通过使用局部变量来完成,或者更简单地通过使 hash 易变)。
class MyClass {
    private int hash;

    public int hashcode() {
        int hash = this.hash;
        if (hash == 0) {
            hash = calculateIt();
            this.hash = hash;
        }
        return hash;
    }
}

关于java - Guava ImmutableMap 中的性能警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454812/

相关文章:

java - jsp如何将选定的值传递给servlet?

java - 如何使用 JPA 解决 javax.persistence.EntityNotFoundException(不是使用 @NotFound)

具有最终用户提供的字段的类的 Java 构造函数

java - 如何为可选参数创建哈希码和等于

java - 正确使用 Guava 两种类型的谓词

java - 发送记录并等待其确认接收

Java 程序适用于大多数但并非所有计算机

java - 大对角矩阵之和 JAVA

java - 在 GWT 中将集合转换到客户端

java - 谷歌公共(public)缓存 - maximumSize 的默认值(和其他 "optional"设置) - 想要一个使用所有 "available"内存的缓存