I'm making a program to calculate all primes up to a specific number. I've been using a timer to optimize the function and I can calculate primes up to 20 million in less than 4 seconds. The problem is, one of the optimizations actually made the program slower, even though it's doing less stuff.
Old function (the faster one):
function getPrimesOld(max) {
const arr = [1];
function isPrime(i) {
const s = Math.sqrt(i);
for (const h of arr) {
if (h === 1) continue;
if (h > s) break;
if (!(i % h)) return false;
}
return true;
}
for (let i = 2 ; i < max ; i += 2) {
if (isPrime(i)) arr.push(i);
if (i === 2) i--;
}
return arr;
}
New function:
function getPrimes(max) {
const arr = [2];
function isPrime(i) {
const s = Math.sqrt(i);
for (const h of arr) {
if (h > s) break;
if (!(i % h)) return false;
}
return true;
}
for (let i = 3 ; i < max ; i += 2) {
if (isPrime(i)) arr.push(i);
}
return arr;
}
I ran both functions 10 times and averaged the time it took them, here are the results:
New function: 3544ms,3188ms,3513ms,3510ms,3511ms,3512ms,3503ms,3515ms,3513ms,3509ms (avg: 3481.8ms)
Old function: 3368ms,3388ms,3363ms,3355ms,3359ms,3350ms,3354ms,3354ms,3353ms,3356ms (avg: 3360ms)
(Just to make it clear, running the old function 10 times first instead of the new one doesn't affect the results. Old always averages around 3.35s and new always averages around 3.5s)
Why is the old function faster than the new one?