Skip to content

Commit

Permalink
Improve SimpleKey hashing function
Browse files Browse the repository at this point in the history
Prior to this commit, `SimpleKey` would be used in Spring Framework's
caching support and its `hashCode` value would be used to efficiently
store this key in data structures.

While the current hashcode strategy works, the resulting values don't
spread well enough when input keys are sequential (which is often the
case). This can have negative performance impacts, depending on the
data structures used by the cache implementation.

This commit improves the `hashCode` function with a mixer to better
spread the hash values. This is using the mixer function from the
MurMur3 hash algorithm.

Closes gh-34483
  • Loading branch information
bclozel committed Feb 25, 2025
1 parent 8b14bf8 commit 466ac6b
Showing 1 changed file with 15 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -30,6 +30,7 @@
*
* @author Phillip Webb
* @author Juergen Hoeller
* @author Brian Clozel
* @since 4.0
* @see SimpleKeyGenerator
*/
Expand All @@ -56,7 +57,7 @@ public SimpleKey(@Nullable Object... elements) {
Assert.notNull(elements, "Elements must not be null");
this.params = elements.clone();
// Pre-calculate hashCode field
this.hashCode = Arrays.deepHashCode(this.params);
this.hashCode = calculateHash(this.params);
}


Expand All @@ -79,7 +80,18 @@ public String toString() {
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
// Re-calculate hashCode field on deserialization
this.hashCode = Arrays.deepHashCode(this.params);
this.hashCode = calculateHash(this.params);
}

/**
* Calculate the hash of the key using its elements and
* mix the result with the finalising function of MurmurHash3.
*/
private static int calculateHash(@Nullable Object[] params) {
int hash = Arrays.deepHashCode(params);
hash = (hash ^ (hash >>> 16)) * 0x85ebca6b;
hash = (hash ^ (hash >>> 13)) * 0xc2b2ae35;
return hash ^ (hash >>> 16);
}

}

0 comments on commit 466ac6b

Please sign in to comment.