Skip to content

Instantly share code, notes, and snippets.

@rktoomey
Created February 23, 2012 02:10
Show Gist options
  • Save rktoomey/1889223 to your computer and use it in GitHub Desktop.
Save rktoomey/1889223 to your computer and use it in GitHub Desktop.
package foo
case class Bar(x: Int, y: Int, z: Int)
object ListHarness {
def time[T](f: => T)(l: Long => Unit): T = {
val t = System.currentTimeMillis
val r = f
l.apply(System.currentTimeMillis - t)
r
}
def main(args: Array[String]) {
val increments = 1 :: 10 :: 100 :: 1000 :: 10000 :: Nil
for (increment <- increments) {
val bars = (1 to increment).map(i => Option(Bar(i, i * 2, i * 3))).toList
method1(bars)
method2(bars)
}
}
def method1(bars: List[Option[Bar]]): Unit = time {
val x = bars.flatMap(_.map(_.x))
val y = bars.flatMap(_.map(_.y))
val z = bars.flatMap(_.map(_.z))
} {
ms =>
println("%s TOTAL: %d entries ---> %d ms".format("method1", bars.size, ms))
}
def method2(bars: List[Option[Bar]]): Unit = time {
val (xx, yy, zz) = bars.foldLeft(List.empty[Int], List.empty[Int], List.empty[Int]) {
case ((x, y, z), bar) =>
(bar.map(_.x).toList ::: x,
bar.map(_.y).toList ::: y,
bar.map(_.z).toList ::: z)
}
} {
ms =>
println("%s TOTAL: %d entries ---> %d ms".format("method2", bars.size, ms))
}
}
method1 TOTAL: 1 entries ---> 2 ms
method2 TOTAL: 1 entries ---> 1 ms
method1 TOTAL: 10 entries ---> 0 ms
method2 TOTAL: 10 entries ---> 0 ms
method1 TOTAL: 100 entries ---> 0 ms
method2 TOTAL: 100 entries ---> 0 ms
method1 TOTAL: 1000 entries ---> 1 ms
method2 TOTAL: 1000 entries ---> 1 ms
method1 TOTAL: 10000 entries ---> 15 ms
method2 TOTAL: 10000 entries ---> 18 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment