Trig Memoization Degrees

JavaScript performance comparison

Test case created by Ippo

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function degSin(deg){ return Math.sin(deg*Math.PI/180); }
    function degCos(deg){ return Math.cos(deg*Math.PI/180); }
    function degTan(deg){ return Math.tan(deg*Math.PI/180); }
   
    function myMemoize(f) {
    /// My own memoization function.
        return function (x) {
                // If the function doesn't have a cache, add one.
                f.cache = f.cache || {};
                // If we've haven't done this before
                if( ! (x in f.cache) ){
                        // Cache it
                        f.cache[x] = f(x);
                }
                return f.cache[x];
        };
    }
    myMemSin = myMemoize(degSin);
    myMemCos = myMemoize(degCos);
    myMemTan = myMemoize(degTan);
   
   
    function memo(f) {
    /// Source: http://philogb.github.com/blog/2008/09/05/memoization-in-javascript/
      return function (x) {
          f.memo = f.memo || {};
          return (x in f.memo)? f.memo[x] : f.memo[x] = f(x);
      };
    }
    memoSin = memoize(degSin);
    memoCos = memoize(degCos);
    memoTan = memoize(degTan);
   
    /*
    * memoize.js
    * by @philogb and @addyosmani
    * with further optimizations by @mathias
    * and @DmitryBaranovsk
    * perf tests: http://bit.ly/q3zpG3
    * Released under an MIT license.
    */
 
    function memoize( fn ) {  
        return function () {  
            var args = Array.prototype.slice.call(arguments),  
                hash = "",  
                i = args.length;  
            currentArg = null;  
            while (i--) {  
                currentArg = args[i];  
                hash += (currentArg === Object(currentArg)) ?  
                JSON.stringify(currentArg) : currentArg;  
                fn.memoize || (fn.memoize = {});  
            }  
            return (hash in fn.memoize) ? fn.memoize[hash] :  
            fn.memoize[hash] = fn.apply(this, args);  
        };  
    }
    otherSin = memoize(degSin);
    otherCos = memoize(degCos);
    otherTan = memoize(degTan);
   
    var deg = Math.random()*360;
};
</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
Non Memoized
degSin(deg);
degCos(deg);
degTan(deg);
pending…
Simple Memoized
myMemSin(deg);
myMemCos(deg);
myMemTan(deg);
pending…
Memo 2
memoSin(deg);
memoCos(deg);
memoTan(deg);
pending…
Complex Memoization
otherSin(deg);
otherCos(deg);
otherTan(deg);
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