Last active
August 29, 2015 14:19
-
-
Save jits/c47f98a2a5a104807c5c to your computer and use it in GitHub Desktop.
Playing with Scala Lists to Maps
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
res1: String = Elapsed time: 46446 microseconds | |
res2: String = Elapsed time: 33675 microseconds | |
res3: String = Elapsed time: 70051 microseconds | |
res4: String = Elapsed time: 40251 microseconds | |
res5: String = Elapsed time: 38201 microseconds | |
res1: String = Elapsed time: 44123 microseconds | |
res2: String = Elapsed time: 65585 microseconds | |
res3: String = Elapsed time: 43811 microseconds | |
res4: String = Elapsed time: 48572 microseconds | |
res5: String = Elapsed time: 49074 microseconds | |
res1: String = Elapsed time: 45099 microseconds | |
res2: String = Elapsed time: 84781 microseconds | |
res3: String = Elapsed time: 44751 microseconds | |
res4: String = Elapsed time: 52398 microseconds | |
res5: String = Elapsed time: 51860 microseconds |
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
def time[R](block: => R): R = { | |
val t0 = System.nanoTime() | |
val result = block // call-by-name | |
val t1 = System.nanoTime() | |
val e = (t1 - t0) / 1000 | |
val s = "Elapsed time: " + e + " microseconds" | |
println(s) | |
result | |
} | |
def time2[R](block: => R): String = { | |
val t0 = System.nanoTime() | |
block // call-by-name | |
val t1 = System.nanoTime() | |
val e = (t1 - t0) / 1000 | |
"Elapsed time: " + e + " microseconds" | |
} | |
class Foo(val x: String, val y: String) | |
val list = (1 to 100000).map { i => new Foo(i.toString, i.toString) }.toList | |
// Perform a simple iteration so we eliminate any chance of cold head/tail caches | |
list.foreach(o => "") | |
time2 { list.map(o => o.x -> o.y).toMap } | |
time2 { list.map(o => (o.x, o.y)).toMap } | |
time2 { list.foldLeft(Map[String, String]())((m, o) => m + (o.x -> o.y)) } | |
time2 { | |
var m = Map[String, String]() | |
list.foreach(o => m += (o.x -> o.y)) | |
} | |
time2 { list.toSeq.map(o => o.x -> o.y).toMap } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment