by SuchAnonMuchWow · 5y ago · 0 comments
const { performance } = require('perf_hooks');
function fib(n) {
if (n == 0 || n == 1) { return 1; }
return fib(n - 1) + fib(n - 2);
}
function fibn(n) {
if (n == 0n || n == 1n) { return 1n; }
return fibn(n - 1n) + fibn(n - 2n);
}
var t0 = performance.now(); fib(35); console.log("fib:", performance.now() - t0);
var t0 = performance.now(); fibn(35n); console.log("fibn:", performance.now() - t0);
results: fib: 127.30008998513222
fibn: 2134.1405459940434
yikes, I think you're right. (nodejs v15.6.0)(An equivalent version with Python on my machine: ~2657.3ms)
JS with number 138 ms (x1)
JS with BigInt (eg. 35n) 2620 ms (x19)
Python 3260 ms (x24)I prefer the JS approach.
I guess node.js might have the edge here with the necessary overflow checks in the addition. Both languages have to do them to fall back to either doubles or bigints respectively, but Node.js's JIT can probably do them faster.