On Sat, Mar 16, 2013 at 11:05:59AM -0400, Rex Kerr wrote:
> P.P.S. Use ScalaMeter or Google Caliper for similar benchmarking.
+100
Rex is right, these kinds of ad-hoc benchmarks don't prove very much.
If you want to know how fast the code will run in production, you need
to allow warmup and such.
It's always possible to write Scala code like Java, so if you are
worried that some Java code is faster than Scala you can always try
writing "Java in Scala" and test it out:
def fib(n: Int): Int = {
var prev1 = 0
var prev2 = 0
var i = 0
while (i < n) {
val savePrev1 = prev1
prev1 = prev2
prev2 = savePrev1 + prev2
i += 1
}
prev1
}
That runs in exactly the same time as Java. Of course, once you get
benchmarking working you'll observe that this ugly code is no faster
than the much nicer:
def fib(n: Int): Int = {
@tailrec def loop(n: Int, a: Int, b: Int): Int =
if (n == 0) a else loop(n - 1, b, a + b)
loop(n, 0, 1)
}
Finally, since Int will overflow on the 47th Fibonacci number, it's
probably wiser to benchmark with BigInteger, or at least Long (which
overflows on the 93rd Fibonacci number).
-- Erik