Created
December 21, 2011 13:13
-
-
Save viktorklang/1505997 to your computer and use it in GitHub Desktop.
Fast, faster, Scala
This file contains hidden or 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
| 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, hope it was helpful