Member-only story

JavaScript is not always faster than Java

JavaScript seems fast because of its efficient network and disk I/O operations

Marian C.
3 min readDec 25, 2021

JavaScripts excels at I/O operations, but it is not the best option for calculations. To demonstrate this well-known fact, I will calculate 40th Fibonacci number using an inefficient algorithm involving lots of operations:

function fibonacci(n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

I measure the execution time of fibonacci(40) using another function measure():

function measure(func) {
const results = [];
for (let i = 0; i < 10; i++) {
const start = Date.now();
const r = await func(40);
const time = (Date.now() - start);
results.push(time);
console.log(i + " " + r + " in " + time);
}
console.log('average: ', average(results));
}
measure(fibonacci);

measure() repeats the calculation 10 times and prints the average time in milliseconds.

In a browser measure(fibonacci) produces output:

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

Responses (2)