Skip to content

Instantly share code, notes, and snippets.

@bpk-t
Created March 21, 2018 01:03
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 bpk-t/a0db62b7859bfed449edca71bf750fcc to your computer and use it in GitHub Desktop.
Save bpk-t/a0db62b7859bfed449edca71bf750fcc to your computer and use it in GitHub Desktop.
object Main extends App {
val list = (1 to 10000).toVector
val start = System.currentTimeMillis()
val a = mapA(list)(_ * 2)
println(s"a elap = ${System.currentTimeMillis() - start}ms")
val start2 = System.currentTimeMillis()
val b = mapB(list)(_ * 2)
println(s"b elap = ${System.currentTimeMillis() - start2}ms")
val start3 = System.currentTimeMillis()
val c = mapC(list)(_ * 2)
println(s"c elap = ${System.currentTimeMillis() - start3}ms")
def mapA[A, B](list: Seq[A])(f: A => B): Seq[B] = list.foldLeft(Seq.empty[B])((acc, x) => acc :+ f(x))
def mapB[A, B](list: Seq[A])(f: A => B): Seq[B] = list.reverse.foldLeft(Seq.empty[B])((acc, x) => f(x) +: acc)
def mapC[A, B](list: Vector[A])(f: A => B): Vector[B] = list.foldLeft(Vector.empty[B])((acc, x) => acc :+ f(x))
}
/*
[info] Running Main
a elap = 1554ms
b elap = 30ms
c elap = 16ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment