Object Creation Patterns. Function Invocation vs Constructor Invocation vs Method Invocation. Plus running their methods (v110)

Revision 110 of this benchmark created by Kim Carter on


Description

Added simple function invocation and tailored the tests to suite the blog post I was writing. Plus added calls to the methods.

The most important thing to remember is to use the right tool for the job. All these tests do is reference an object with a complex memory allocation. When you don't need something fancy, you're better off using a regular old object

Setup

// Setup function constructor.
    var AFunctionConstructor = function () {
       var myString = 'a string';
       var foo = function () {
          return myString;
       };
       this.bar = function () {
          return foo();
       };
    };
    
    // Setup function constructor with functions added to the prototype.
    var AFunctionConstructorWithPrototypeAdditions = function () {
       this.myString = 'a string';
    };
    AFunctionConstructorWithPrototypeAdditions.prototype.foo = function () {
       return this.myString;
    };
    AFunctionConstructorWithPrototypeAdditions.prototype.bar = function () {
       return this.foo(); // think we need this here.
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Simple function invocation. Plus method call.
var myFunctionInvocation = function () {
   var myString = 'a string';
   var foo = function () {
      return myString;
   };
   return function () {
      return foo();
   }();
};
myFunctionInvocation();
ready
Function constructor invocation. Plus method call.
var myFunctionConstructor = new AFunctionConstructor();
myFunctionConstructor.bar();
ready
Function constructor invocation with functions added to the prototype. Plus method call.
var myFunctionConstructorWithPrototypeAdditions = new AFunctionConstructorWithPrototypeAdditions();
myFunctionConstructorWithPrototypeAdditions.bar();
ready
Object literal invocation. Plus method call.
var myObjectLiteral = {
   myString: 'a string',
   foo: function () {
      return this.myString;
   },
   bar: function () {
      return this.foo();
   }
};
myObjectLiteral.bar();
ready

Revisions

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