Skip to content

Commit

Permalink
OpenHashMap.mergeX: Avoid triple-hashing key
Browse files Browse the repository at this point in the history
Previously, we were hashing the key 3x:
- get
- containsKey
- put

Now, we override mergeDouble with a hashamp-specific implementation that
hashes the key once.

Towards vigna#336
  • Loading branch information
mhansen committed Nov 20, 2024
1 parent 044c3dc commit 87bb74c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
19 changes: 19 additions & 0 deletions drv/OpenHashMap.drv
Original file line number Diff line number Diff line change
Expand Up @@ -1253,6 +1253,25 @@ public class OPEN_HASH_MAP KEY_VALUE_GENERIC extends ABSTRACT_MAP KEY_VALUE_GENE
return value[pos] = newVal;
}

#if VALUES_PRIMITIVE && ! VALUE_CLASS_Boolean
/** {@inheritDoc} */
@Override
public VALUE_GENERIC_TYPE MERGE_VALUE(final KEY_GENERIC_TYPE k, final VALUE_GENERIC_TYPE v, METHOD_ARG_VALUE_BINARY_OPERATOR remappingFunction) {
java.util.Objects.requireNonNull(remappingFunction);
REQUIRE_VALUE_NON_NULL(v)

final int pos = find(k);
if (pos < 0) {
insert(-pos - 1, k, v);
return v;
}

final VALUE_GENERIC_TYPE newValue = remappingFunction.VALUE_OPERATOR_APPLY(value[pos], v);

return value[pos] = newValue;
}
#endif

/** {@inheritDoc} */
@Override
public VALUE_GENERIC_TYPE merge(final KEY_GENERIC_TYPE k, final VALUE_GENERIC_TYPE v, final java.util.function.BiFunction<? super VALUE_GENERIC_CLASS, ? super VALUE_GENERIC_CLASS, ? extends VALUE_GENERIC_CLASS> remappingFunction) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,13 @@ public int hashCode() {
}
}

// Regression test for https://github.com/vigna/fastutil/pull/337.
@Test
public void testMergeIntHashesKeyMultipleTimes() {
public void testMergeIntHashesKeyOnce() {
Object2IntOpenHashMap m = new Object2IntOpenHashMap(Hash.DEFAULT_INITIAL_SIZE);
HashCounter hc = new HashCounter();
m.mergeInt(hc, 0, Math::max);
assertEquals(3, hc.hashCount);
assertEquals(1, hc.hashCount);
}
}

0 comments on commit 87bb74c

Please sign in to comment.