5 ms·
Doesn't the Node.js version use double precision floating point vs python using infinite precision integers ? That would explain part of the difference in perfo
by SuchAnonMuchWow 6y ago
Doesn't the Node.js version use double precision floating point vs python using infinite precision integers ?
That would explain part of the difference in performance, and make the python version exact, but js version inexact.
- nullcat 6y agoThat's one factor but there is an overall reason behind performance difference. The main reason is v8 and the inordinate amount of resources google has thrown against that thing to make it ultra fast. You should read up on the people who work on it.
- d0mine 6y agoThe numbers are small so there shouldn’t be any difference for fib(35)
- meetups323 6y agoThis is correct, though both are exact at the scales in question (14930352). There's a more general question of whether it's beneficial to take a perf hit for all arithmetic in order to support some corner cases of infinite precision, or be explicit that standard arithmetic won't be precise, but you can opt into it via some mechanism (BigNum, in the JS case) I prefer the JS approach.
- wongarsu 6y agoThe specifications do say that JavaScript only has floating point numbers (and no integers) and that Python has infinite precision integers. But in implementation, for whole numbers small enough to fit into a regular 32-bit integer both Python and Node.js use regular integers as an optimization. fib(35) comfortably fits that. 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.
- akubera 6y agoI assumed since this seems to be testing function call overhead, rather than the math, that an equivalent function with BigIntegers would be about the same for JS. But I tried it just for fun: 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)
- edflsafoiewq 6y agoThis looks like most of the difference. JS with number 138 ms (x1) JS with BigInt (eg. 35n) 2620 ms (x19) Python 3260 ms (x24)