Created
November 28, 2014 10:28
-
-
Save ldacosta/0c5580fb5b91ba8cde07 to your computer and use it in GitHub Desktop.
What is fastest to do when filling up a Map?
This file contains hidden or 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 generateRandom(length: Int): String = scala.util.Random.alphanumeric.take(length).mkString("") | |
def timeInMs[R](block: => R): (Long, R) = { | |
val t0 = System.currentTimeMillis() | |
val result = block // call-by-name | |
val t1 = System.currentTimeMillis() | |
((t1 - t0), result) | |
} | |
val howManyFields = 10 | |
val fieldNames = (1 to howManyFields).map(_ => generateRandom(10)).toArray | |
val howManyRuns = 100000 | |
// with a map: | |
val (time1, m1) = | |
timeInMs { | |
(1 to howManyRuns).foldLeft(Map.empty[String, List[String]]) { (m, _) => | |
val fieldName = fieldNames(scala.util.Random.nextInt(howManyFields)) | |
val newValue = generateRandom(10) | |
m + (fieldName -> (m.getOrElse(fieldName, List.empty) ++ List(newValue))) | |
} | |
} | |
// with a list + groupBy: | |
val (time2, m2) = { | |
timeInMs { | |
val x = | |
(1 to howManyRuns).foldLeft(List.empty[(String, String)]) { (m, _) => | |
val fieldName = fieldNames(scala.util.Random.nextInt(howManyFields)) | |
val newValue = generateRandom(10) | |
m ++ List((fieldName, newValue)) | |
} | |
x.groupBy(r => r._1).map{case (k,v) => k -> v.map(_._2)} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment