Currently, I am conducting a Fibonacci benchmark on my Android phone and the results are quite unusual. Interestingly, I am not concerned about whether the UI-thread is locked or not, so I have decided to run the following code within the UI-thread of my application (could this potentially impact performance?).
public void startBenchmark(View view) {
results = "";
results += String.format("Begin test");
for (int i = 45; i < 46; i++) {
startTime = System.currentTimeMillis();
fib(i);
results += String.format("%d\n", System.currentTimeMillis() - startTime);
}
results += String.format("End test");
Log.d("Results", results);
Log.d("Status", "Finished");
}
private static int fib(int n) {
return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}
In addition, I have also created a similar code in JavaScript;
function performBenchmark() {
for (var i = 45; i < 46; i++) {
benchmark(i)
}
}
function benchmark(n){
var start= Date.now();
document.getElementById("disp").innerHTML += "fib(" + n + "): " + fib(n) + " <br />";
document.getElementById("results").innerHTML += (Date.now() - start) + "<br />";
}
function fib(n) {
return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}
I am encountering an issue with fib(45) where the native Java platform is taking around 420 seconds while JavaScript in Chrome only takes 120 seconds when running on my Samsung Galaxy Nexus.
Could there be a glaring issue in my Java implementation for Android that is causing this slowdown in the benchmark?
Note: My main focus is not on transitioning to a quicker algorithm but rather understanding why JavaScript (and even an iOS implementation I worked on) outperform the Java implementation for Android significantly.
Interestingly, when running the tests on my laptop, Java performs much faster than JavaScript.