methods on object vs redefining methods on each call

Benchmark created by ryan on


Description

Testing to see if redefining function methods are slower when called repeatedly vs having them defined once on the object and then accessing it

Setup

var objFnSameLevel = {
      method1: function(arg1, arg2) {
        return arg1 + arg2;
      }
      , method2: function(myArg) {
        return myArg + 2;
      }
      , method3: function(myArg) {
        return this.method1(myArg, this.method2(myArg));
      }
    };
    
    
    var objFnNested = {
      methods: function(myArg) {
        var thisArg = myArg;
        var method1 = function(arg1, arg2) {
          return arg1 + arg2;
        };
    
        var method2 = function(myArg) {
          return myArg + 2;
        };
    
        var method3 = function(myArg) {
          return method1(myArg, method2(myArg));
        };
    
        return method3(thisArg);
     }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Functions on same level as object, defined once and accessed
var o1 = objFnSameLevel;
o1.method3(3);
ready
Functions nested, redefined each time
var o2 = objFnNested;
o2.methods(3);
ready

Revisions

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