Ask HN: Why is JavaScript fast than C++ for simple calculations?
I was able to improve the speed from 6 seconds with a simple algorithm to 33 milliseconds with a more improved algorithm (looking for all primes up to 50k here, a more detailed description can be found there [1][2], this is the simple "algorith" - not much surprising:
def isPrime(number):
for i in range(2, number):
if (number % i) == 0:
return False
return True
So I tried the same for JavaScript. The simple algorithm took 212 milliseconds, the improved one finished after 3 milliseconds.So I wondered, what else can I test? I increased the upper bounds to 100 Mio. JavaScript took around 40 seconds. Using Cything I was able improve the running time to 70 seconds.
And I also tried Rust and C++ (disclaimer: I'm not a Rust or C++ developer!)
Rust was a desaster, I had to stop it after 5 Minutes. The first compiliation for C++ leads to a algorithm that tooks 70 seconds - almost double the time as JavaScript! After a little research I found out, that I can tune the compiling a little, which leads to a running time of 40 seconds.
So, still I wonder, in simple words: How can JavaScript be as fast as C++? (which probably only applies to simple mathmatics...)
[1] https://nickyreinert.medium.com/how-to-find-prime-numbers-fast-8d0f7e8bd80f
[2] https://nickyreinert.medium.com/javascript-how-to-find-prime-numbers-fast-cbcf6bd62e3d