Skip to content

Instantly share code, notes, and snippets.

@ldacosta
Created November 28, 2014 10:28
Show Gist options
  • Save ldacosta/0c5580fb5b91ba8cde07 to your computer and use it in GitHub Desktop.
Save ldacosta/0c5580fb5b91ba8cde07 to your computer and use it in GitHub Desktop.
What is fastest to do when filling up a Map?
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