Skip to content

Instantly share code, notes, and snippets.

@viktorklang
Created December 21, 2011 13:13
Show Gist options
  • 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)
}
}
@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