Skip to content

Commit 10612a8

Browse files
authored
Merge pull request scala/scala#8655 from rorygraves/mike/2.12.x_quickHashWithoutIntRef
avoid creating IntRefs and streamline some hashing operations
2 parents 7d72438 + 480b40e commit 10612a8

File tree

1 file changed

+37
-19
lines changed

1 file changed

+37
-19
lines changed

library/src/scala/util/hashing/MurmurHash3.scala

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -96,31 +96,49 @@ private[hashing] class MurmurHash3 {
9696
* This is useful for hashing sets, for example.
9797
*/
9898
final def unorderedHash(xs: TraversableOnce[Any], seed: Int): Int = {
99-
var a, b, n = 0
100-
var c = 1
101-
xs foreach { x =>
102-
val h = x.##
103-
a += h
104-
b ^= h
105-
if (h != 0) c *= h
106-
n += 1
99+
if (xs.isEmpty) {
100+
var h = seed
101+
h = mix(h, 0)
102+
h = mix(h, 0)
103+
h = mixLast(h, 1)
104+
finalizeHash(h, 0)
105+
}
106+
else {
107+
object hasher extends Function1[Any, Unit] {
108+
var a, b, n = 0
109+
var c = 1
110+
override def apply(x: Any): Unit = {
111+
val h = x.##
112+
a += h
113+
b ^= h
114+
if (h != 0) c *= h
115+
n += 1
116+
}
117+
}
118+
xs foreach hasher
119+
var h = seed
120+
h = mix(h, hasher.a)
121+
h = mix(h, hasher.b)
122+
h = mixLast(h, hasher.c)
123+
finalizeHash(h, hasher.n)
107124
}
108-
var h = seed
109-
h = mix(h, a)
110-
h = mix(h, b)
111-
h = mixLast(h, c)
112-
finalizeHash(h, n)
113125
}
114126
/** Compute a hash that depends on the order of its arguments.
115127
*/
116128
final def orderedHash(xs: TraversableOnce[Any], seed: Int): Int = {
117-
var n = 0
118-
var h = seed
119-
xs foreach { x =>
120-
h = mix(h, x.##)
121-
n += 1
129+
if (xs.isEmpty) finalizeHash(seed, 0)
130+
else {
131+
object hasher extends Function1[Any, Unit] {
132+
var n = 0
133+
var h = seed
134+
override def apply(x: Any): Unit = {
135+
h = mix(h, x.##)
136+
n += 1
137+
}
138+
}
139+
xs foreach hasher
140+
finalizeHash(hasher.h, hasher.n)
122141
}
123-
finalizeHash(h, n)
124142
}
125143

126144
/** Compute the hash of an array.

0 commit comments

Comments
 (0)