Constructor that supports either class([]) or new Class();

JavaScript performance comparison

Revision 2 of this test case created by Nook

Preparation code

<script>
(function (window) {
  var K = function () {}
    , document = window.document;

  var Constructor1 = function () {
    var self;
    if (this instanceof Constructor1)
      self = this;
    else      
      self = new K();

    return self;
  }

  K.prototype = Constructor1.prototype;

  Constructor1.prototype.pipe = function (data) {
    return data;
  }
 
  window.Constructor1 = Constructor1;
})(this);
</script>
<script>
(function (window) {
  var document = window.document;

  var Constructor2 = function () {
    if (!(this instanceof Constructor2))
      return new Constructor2();
  }

  Constructor2.prototype.pipe = function (data) {
    return data;
  }

  window.Constructor2 = Constructor2;
})(this)
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
1
var a1 = Constructor2();
var a2 = a1.pipe('data');
pending…
2
var a1 = Constructor1();
var a2 = a1.pipe('data');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment