Detect prime numbers

JavaScript performance comparison

Test case created by Devon Govett

Preparation code

<script>
  var arr = [
   7, // true
   10, // false
   37, // true
   60, // false
   373, // true
   390, // false
   1427, // true
   1683, // false
   7879, // true
   7881 // false
  ];
  
  // Code taken from http://ejohn.org/apps/learn/ by John Resig
  function isPrime(num) {
   var prime = num != 1; // Everything but 1 can be prime
   for (var i = 2; i < num; i++) {
    if (num % i == 0) {
     prime = false;
     break;
    };
   };
   return prime;
  };
  
  function isPrimeCached(num) {
   if (isPrimeCached.cache[num] !== null) {
    return isPrimeCached.cache[num];
   };
   var prime = num != 1; // Everything but 1 can be prime
   for (var i = 2; i < num; i++) {
    if (num % i == 0) {
     prime = false;
     break;
    };
   };
   isPrimeCached.cache[num] = prime;
   return prime;
  };
  isPrimeCached.cache = {};
  
  // Code by Devon Govett — http://twitter.com/devongovett/status/20019256843, inspired by http://mths.be/ahf
  function isPrimeRegex(n) {
   return Array(n + 1).join('1').search(/^1?$|^(11+?)\1+$/) === -1;
  };
</script>
    

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
isPrime()
var i = arr.length;
while (i--) {
 isPrime(arr[i]);
};
pending…
isPrimeCached()
var i = arr.length;
while (i--) {
 isPrimeCached(arr[i]);
};
pending…
isPrimeRegex()
var i = arr.length;
while (i--) {
 isPrimeRegex(arr[i]);
};
pending…

Compare results of other browsers

Revisions

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

0 Comments