Created
April 29, 2017 09:26
-
-
Save channingwalton/f11573a42c394db7d2fac912a57fb530 to your computer and use it in GitHub Desktop.
Benchmark for performance of .toSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package set.performance | |
import java.util.concurrent.TimeUnit | |
import scala.concurrent.duration.FiniteDuration | |
/** | |
* On my machine the fast method takes < 2 ms, the slow one 2.2s | |
*/ | |
object SetPerformance { | |
val keys: Set[Int] = Set(1, 2, 3) | |
val map: Map[Int, Int] = (0 until 10000).map(x ⇒ (x, x)).toMap | |
val iterations = 10000 | |
val testLoops = 10 | |
def main(args: Array[String]): Unit = (1 to testLoops).foreach{ iteration ⇒ | |
println(s"Running slow $iteration") | |
println(time(slow())) | |
println(s"Running fast $iteration") | |
println(time(fast())) | |
println() | |
} | |
private def slow() = | |
(0 until iterations) foreach { _ ⇒ | |
// everything up to the toSet is very fast (comment the toSet out to see) | |
// the problem is toSet | |
map.filterKeys(keys).values.toSet | |
} | |
private def fast() = | |
(0 until iterations) foreach { _ ⇒ | |
keys.flatMap(map.get) | |
} | |
def time[T](f: ⇒ T): FiniteDuration = { | |
val start = System.currentTimeMillis() | |
f | |
val end = System.currentTimeMillis() | |
FiniteDuration(end - start, TimeUnit.MILLISECONDS) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment