Skip to content

Commit 9d499d7

Browse files
committed
Benchmark for groupBy
1 parent e32b224 commit 9d499d7

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Scala (https://www.scala-lang.org)
3+
*
4+
* Copyright EPFL and Lightbend, Inc.
5+
*
6+
* Licensed under Apache License 2.0
7+
* (http://www.apache.org/licenses/LICENSE-2.0).
8+
*
9+
* See the NOTICE file distributed with this work for
10+
* additional information regarding copyright ownership.
11+
*/
12+
13+
package scala.collection
14+
15+
16+
import java.util.concurrent.TimeUnit
17+
import org.openjdk.jmh.annotations.{Benchmark, BenchmarkMode, Fork, Level, Measurement, Mode, OutputTimeUnit, Param, Scope, Setup, State, Threads, Warmup}
18+
import org.openjdk.jmh.infra.Blackhole
19+
import scala.collection.mutable.ArrayBuffer
20+
21+
22+
@BenchmarkMode(Array(Mode.AverageTime))
23+
@Fork(2)
24+
@Threads(1)
25+
@Warmup(iterations = 10)
26+
@Measurement(iterations = 10)
27+
@OutputTimeUnit(TimeUnit.NANOSECONDS)
28+
@State(Scope.Benchmark)
29+
class GroupByBenchmark {
30+
@Param(Array("128", "512", "2048", "8192"))
31+
var size : Int = _
32+
33+
@Param(Array("0", "32"))
34+
var hashCodeCost: Int = _
35+
36+
@Param(Array("8", "2147483647"))
37+
var maxNumGroups: Int = _
38+
39+
private case class Key(a: Int) {
40+
override def hashCode(): Int = {
41+
Blackhole.consumeCPU(hashCodeCost)
42+
Integer.hashCode(a)
43+
}
44+
}
45+
46+
private case class Groupable(a: Int) {
47+
val key = new Key(a % maxNumGroups)
48+
}
49+
50+
private var groupables: ArrayBuffer[Groupable] = _
51+
52+
private class GroupByWrapper[A](as: collection.Iterable[A]) extends collection.Iterable[A] {
53+
override def iterator: Iterator[A] = as.iterator
54+
override protected def newBuilder = new mutable.Builder[A, Iterable[A]] {
55+
override def clear(): Unit = ()
56+
override def result(): Iterable[A] = Nil
57+
override def +=(elem: A): this.type = this
58+
}
59+
}
60+
61+
@Setup(Level.Trial) def setup(): Unit = {
62+
groupables = ArrayBuffer.tabulate(size)(Groupable(_))
63+
}
64+
65+
@Benchmark def buildArrayBuffer(): AnyRef = {
66+
groupBy(groupables)
67+
}
68+
@Benchmark def buildNil(): AnyRef = {
69+
groupBy(new GroupByWrapper[Groupable](groupables))
70+
}
71+
72+
private def groupBy[B](as: collection.Iterable[Groupable]) = as.groupBy(_.key)
73+
}

0 commit comments

Comments
 (0)