Skip to content

Instantly share code, notes, and snippets.

@sherifkandeel
Created October 28, 2019 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sherifkandeel/ce7fe9b88397712cedd6f32a20a21839 to your computer and use it in GitHub Desktop.
Save sherifkandeel/ce7fe9b88397712cedd6f32a20a21839 to your computer and use it in GitHub Desktop.
Comparing different ways to get minimum of a collection
case class TestCaseClass(cost: Float, other1: Int, other2: String, other3: String)
val r = new scala.util.Random(31)
val tenkList = 1 to 10000 map (_ => TestCaseClass(r.nextFloat(), r.nextInt, r.alphanumeric.take(3).mkString, ""))
val millionList = 1 to 1000000 map (_ => TestCaseClass(r.nextFloat(), r.nextInt, r.alphanumeric.take(3).mkString, ""))
val tenMillionList = 1 to 10000000 map (_ => TestCaseClass(r.nextFloat(), r.nextInt, r.alphanumeric.take(3).mkString, ""))
def time[R](block: => R): Long = {
val t0 = System.currentTimeMillis()
block
val t1 = System.currentTimeMillis()
t1 - t0
}
def min(o1: TestCaseClass, o2: TestCaseClass) = if (o1.cost < o2.cost) o1 else o2
println(s"10k: minBy ${time{tenkList.minBy(_.cost)}} and reduce ${time {tenkList.reduce(min)}}")
println(s"1M: minBy ${time{millionList.minBy(_.cost)}} and reduce ${time {millionList.reduce(min)}}")
println(s"10M: minBy ${time{tenMillionList.minBy(_.cost)}} and reduce ${time {tenMillionList.reduce(min)}}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment