I am testing a memoized recursive version for finding the Fibonacci number at a given point (I'm using 50). The execution time in Java is instantaneous, while on Scala it takes around 65-67 seconds. This is is the Scala code:
def fibonacciDP(array : Array[Long] , counter : Int) : Long = {
if (array(counter) != 0L) array(counter)
if (counter == 1 || counter == 2) 1L
else {
val result = fibonacciDP(array, counter - 1) + fibonacciDP(array, counter - 2)
array(counter) = result
result
}
}
This is the Java code:
private static long fibonacciDP(long[] array, int counter) {
if (!(array[counter] == 0L)) {
return array[counter];
}
if (counter == 1 || counter == 2) return 1L;
final long result = fibonacciDP(array,counter - 1) + fibonacciDP(array, counter - 2);
array[counter] = result;
return result;
}
I test them like this in:
Scala:
def main(args: Array[String]): Unit = {
val counter = 50
val array = Array.fill(counter+1){0L}
val startTime = System.currentTimeMillis()
println(startTime)
val result = fibonacciDP(array,counter)
println(result)
val endTime = System.currentTimeMillis()
println(endTime - startTime)
}
Java:
public static void main(String[] args) {
final int counter = 50;
long[] array = new long[50+1];
final long startTime = System.nanoTime();
final long fiboNum = fibonacciDP(array,counter);
final long endTime = System.nanoTime();
System.out.println((endTime - startTime)/1000000);
}
Then I added the return
keyword to the values inside the first two conditions in the Scala function, the speed of execution dropped to 4ms average (3-5ms range).
Why is there a difference in execution speeds?