Skip to content

Instantly share code, notes, and snippets.

@viktorklang
Created December 21, 2011 13:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save viktorklang/1505997 to your computer and use it in GitHub Desktop.
Save viktorklang/1505997 to your computer and use it in GitHub Desktop.
Fast, faster, Scala
object Scala extends App {
import scala.collection.mutable.ArrayBuffer
import scala.annotation.tailrec
val items = List("foo", 23, true)
val before = System.currentTimeMillis()
@tailrec def adds(n: Int, absoluteResult: ArrayBuffer[Any] = ArrayBuffer()): ArrayBuffer[Any] = {
def foo(obj : Any) = obj match {
case _:String => "String"
case _:Boolean => "Boolean"
case _:Integer => "Integer"
case _ => throw new IllegalArgumentException()
}
@tailrec def add(s: List[Any]): Unit = if (s.nonEmpty) {
absoluteResult += foo(s.head)
add(s.tail)
}
if(n > 0) {
add(items)
adds(n - 1, absoluteResult)
} else absoluteResult
}
{
val absoluteResult = adds(1000000)
println("Took : "+(System.currentTimeMillis() - before) + " ms, number of elements : "+absoluteResult.size)
}
}
@danieldietrich
Copy link

Wooohooo! Tried to speed up the code of Sven today. But THIS is amazing!!
Your version is nearly 56 times faster than the first version on Sven's blog and even more than 3 times faster than the optimized version posted there (measured on my machine).

  • Daniel

@viktorklang
Copy link
Author

Thanks, hope it was helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment