Created
March 4, 2017 03:38
-
-
Save ThibautGery/4783181e00360832c27bcca46c274980 to your computer and use it in GitHub Desktop.
Benchmark to check the execution time of takeWhile using local state and local immutable structure
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
class TakeWhileBenchmark { | |
def takeWhile1[A](list: List[A])(f: A => Boolean): List[A]= { | |
@tailrec | |
def go(list: List[A], acc: List[A]): List[A] = { | |
list match { | |
case x :: xs if f(x) => go(xs, x :: acc) | |
case _ => acc | |
} | |
} | |
go(list, List()).reverse | |
} | |
def takeWhile2[A](list: List[A])(p: A => Boolean): List[A] = { | |
val b = new ListBuffer[A] | |
var these = list | |
while (!these.isEmpty && p(these.head)) { | |
b += these.head | |
these = these.tail | |
} | |
b.toList | |
} | |
def benchLocalState(limit: Int) { | |
val input = (1 to 100000).toList | |
val time = 1 to 10000 | |
val start = System.currentTimeMillis() | |
time.foreach { | |
_ => takeWhile2(input)(_ <= limit) | |
} | |
val stop = System.currentTimeMillis() | |
print(s"duration: ${ stop - start }") | |
} | |
def benchNoState(limit: Int) { | |
val input = (1 to 100000).toList | |
val time = 1 to 10000 | |
val start = System.currentTimeMillis() | |
time.foreach { | |
_ => takeWhile1(input)(_ <= limit) | |
} | |
val stop = System.currentTimeMillis() | |
print(s"duration: ${ stop - start }") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment