isPrime

JavaScript performance comparison

Test case created by Renosis

Info

Testing a hopefully more optimized version of my isPrime function, versus an older version.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Old isPrime
for(var i = 0; i < 10000; i++) {
 isPrime(i);
}

function isPrime(n) {    
    if(n === 1 || n < 1 || (n > 5 && n % 5 === 0) || (n > 2 && n % 2 === 0) || (n > 3 && n % 3 === 0) || (n > 7 && n % 7 === 0)) { return false; }
    for(var i = 2; i <= Math.sqrt(n); i++) {

        if(n % i === 0) { return false; }

        }

    return true;

    }
pending…
New isPrime
for(var i = 0; i < 10000; i++) {
 isPrime(i);
}
function isPrime(n) {
    if(n === 2) { return true; }
    if(n === 1 || n < 1 || (n > 5 && n % 5 === 0) || (n % 2 === 0) || (n > 3 && n % 3 === 0) || (n > 7 && n % 7 === 0)) { return false; }
    var limit = Math.sqrt(n);
    for(var i = 3; i <= limit; i+= 2) {
        if(n % i === 0) { return false; }
        }
    return true;
    }
pending…
New isPrime minus conditionals
for(var i = 0; i < 10000; i++) {
 isPrime(i);
}
function isPrime(n) {
    if(n === 2) { return true; }
    if(n === 1) { return false; }
    var limit = Math.sqrt(n);
    for(var i = 3; i <= limit; i+= 2) {
        if(n % i === 0) { return false; }
        }
    return true;
    }
pending…
Old isPrime with limit
for(var i = 0; i < 10000; i++) {
 isPrime(i);
}

function isPrime(n) {    
    if(n === 1 || n < 1 || (n > 5 && n % 5 === 0) || (n > 2 && n % 2 === 0) || (n > 3 && n % 3 === 0) || (n > 7 && n % 7 === 0)) { return false; }
    var limit = Math.sqrt(n);
    for(var i = 2; i <= limit; i++) {

        if(n % i === 0) { return false; }

        }

    return true;

    }
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment