Trig Memoization Radians

Benchmark created by Ippo on


Description

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

Setup

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();

Test runner

Ready to run.

Testing in
TestOps/sec
Non-Memoized
Math.sin(rad);
Math.cos(rad);
Math.tan(rad);
ready
Simple Memoized
myMemSin(rad);
myMemCos(rad);
myMemTan(rad);
ready
Alt Memo
memoSin(rad);
memoCos(rad);
memoTan(rad);
ready
Other Memoized
otherSin(rad);
otherCos(rad);
otherTan(rad);
ready

Revisions

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

  • Revision 1: published by Ippo on