Caching-prime-calculator

JavaScript performance comparison

Test case created by Nathaniel Higgins

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var calculate = function(calculations, value) {
   
        if (calculations) {
            if (calculations[value]) {
                return calculations[value];
            }
        }
   
        var prime = value !== 1;
   
        if (prime) {
            for (var i = 2; i < value; i++) {
                if (value % i === 0) {
                    prime = false;
                    break;
                }
            }
        }
   
        if (calculations) {
            calculations[value] = prime;
        }
   
        return prime;
    };
   
    var isPrime = {
        cacheAsProperty: function isPrime(value) {
            if (!isPrime.calculations) {
                isPrime.calculations = {};
            }
   
            return calculate(isPrime.calculations, value);
        },
   
        cacheAsVariableInClosure: (function() {
   
            var calculations = {};
   
            return function(value) {
                return calculate(calculations, value);
            }
   
        })(),
   
        dontCache: function(value) {
            return calculate(false, value);
        }
    }
   
    var assert = function(result) {
        if (!result) {
            throw 'Broken test';
        }
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Dont Cache
// Test it works
assert(isPrime.dontCache(17) === true);
assert(isPrime.dontCache(25) === false);

// Calculate primes for 1-1000
for (var i = 0, l = 1000; i <= l; i++) {
    isPrime.dontCache(i);
}
pending…
Cache as property
// Test it works
assert(isPrime.cacheAsProperty(17) === true);
assert(isPrime.cacheAsProperty(25) === false);

// Calculate primes for 1-1000
for (var i = 0, l = 1000; i <= l; i++) {
    isPrime.cacheAsProperty(i);
}
pending…
Cache as variable in closure
// Test it works
assert(isPrime.cacheAsVariableInClosure(17) === true);
assert(isPrime.cacheAsVariableInClosure(25) === false);

// Calculate primes for 1-1000
for (var i = 0, l = 1000; i <= l; i++) {
    isPrime.cacheAsVariableInClosure(i);
}
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