NodeJS vs. Python 3 Performance
Warren Wong
Posted on April 25, 2019
Originally published at warrenwong.org.
While trying to become more Pythonic in my coding, I have been going over some of my Project Euler toy problems. It's mostly fun and cathartic, but I did notice something fairly interesting.
On problem 7 of Project Euler, the solution seems fairly simple to implement. My implementation for both is rather similar (no real obvious way to make it utilize some of the newer features of JavaScript or Python 3 that I can see). My assumptions was that it would take about the same amount of time to run.
NodeJS implementation:
const isPrime = n => {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
};
const getPrime = n => {
let count = 0;
let num = 2;
while (n > count) {
if (isPrime(num)) {
count += 1;
}
num += 1;
}
return num - 1;
};
Python implementation:
def is_prime(n):
for i in range(2, n):
if (n % i == 0):
return False
return True
def get_prime(n):
count = 0
num = 2
while n > count:
if is_prime(num):
count += 1
num += 1
return num - 1
I mean, it's fairly simple and straight-forward. The time complexity of both should be exactly the same, but I couldn't believe the difference. I ran it several times with the Unix time
utility and I consistently got sub 2 seconds for the NodeJS implementation and over 25 seconds for Python 3.
It's actually incredibly alarming for me to see the difference since I would think the performance would be fairly similar. Since I was curious, seems like other more "formal" benchmarks also confirm this.
Well color me surprised.
Posted on April 25, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.