Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.