Created
March 21, 2018 01:03
-
-
Save bpk-t/a0db62b7859bfed449edca71bf750fcc to your computer and use it in GitHub Desktop.
This file contains 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
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