Skip to content

Instantly share code, notes, and snippets.

@ThibautGery
Created March 4, 2017 03:38
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 ThibautGery/4783181e00360832c27bcca46c274980 to your computer and use it in GitHub Desktop.
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
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