Node.js 14 is over 2x faster than OpenJDK HotSpot Java 15 for fib(n)
Not the most comprehensive benchmark, but the results are surprising to me.
// (Node.js v14.14.0)
const {
performance
} = require('perf_hooks');
function fib(n) {
let num1 = 0;
for (let i = 0, num2 = 1; i < n; ++i) {
let num3 = (num2 + num1);
num1 = num2;
num2 = num3;
}
return num1;
}
const t0 = performance.now();
console.log(fib(40));
const t1 = performance.now();
console.log(`${t1 - t0} ms`);
First run: 18ms
Second run: 9ms
// (openjdk 15.0.2 HotSpot)
class Fib {
static int fib(int n) {
int num1 = 0;
for (int i = 0, num2 = 1; i < n; ++i) {
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
}
return num1;
}
public static void main(String args[]) {
long startTime = System.nanoTime();
System.out.println(fib(40));
long stopTime = System.nanoTime();
System.out.println((stopTime - startTime) / 1000000);
}
}
First run: 40ms
Second run: 20ms