Trig Memoization Radians

JavaScript performance comparison

Test case created by Ippo

Info

This tests if memoizing javascript's build-in trig functions (Math.sin, Math.cos, etc...) has any performance benefits when working with radians.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    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(Math.sin);
    myMemCos = myMemoize(Math.cos);
    myMemTan = myMemoize(Math.tan);
   
   
    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(Math.sin);
    memoCos = memoize(Math.cos);
    memoTan = memoize(Math.tan);
   
    /*
    * 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(Math.sin);
    otherCos = memoize(Math.cos);
    otherTan = memoize(Math.tan);
   
    var rad = Math.random();
};
</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
Math.sin(rad);
Math.cos(rad);
Math.tan(rad);
pending…
Simple Memoized
myMemSin(rad);
myMemCos(rad);
myMemTan(rad);
pending…
Alt Memo
memoSin(rad);
memoCos(rad);
memoTan(rad);
pending…
Other Memoized
otherSin(rad);
otherCos(rad);
otherTan(rad);
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