Guava ImmutableMap has noticeably slower access than HashMap

前端 未结 2 1655
渐次进展
渐次进展 2021-02-02 07:28

While working on a memory benchmark of some high-throughput data structures, I realized I could use an ImmutableMap with only a little refactoring.

Thinki

相关标签:
2条回答
  • 2021-02-02 07:44

    Some possible reasons:

    1. Could that depend on your implementation of RndString.build()?

    2. And have a look at the get() implementation of both maps: com.google.common.collect.RegularImmutableMap.get(Object) java.util.HashMap.getEntry(Object) java.util.HashMap tries to compare with "==" first. RegularImmutableMap doesn't. That may speed up

    3. Could a different load factor be responsible for that? Perhaps the RegularImmutableMap needs more iterations to find the correct entry.

    0 讨论(0)
  • 2021-02-02 07:52

    As Louis Wasserman said, ImmutableMap is not optimized for objects with slow equals method. I think the main difference is here:

    HashMap:

    if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
        return e.value;
    

    ImmtubleMap:

    if (key.equals(candidateKey)) {
        return entry.getValue();
    

    As you can see, to check for collisions, HashMap first check the hashes. This allows to reject values with different hashes fast. Since String doesn't make this check in its equals method, this makes HashMap faster. ImmutableMap doesn't use this optimization because it would make the test slower when equals is already optimized.

    0 讨论(0)
提交回复
热议问题