Constructors with Array Parameters

JavaScript performance comparison

Test case created by Jasdeep Khalsa

Info

Since I love arrays so much (doesn't everybody?) I wanted to test the fastest way of creating an object from a constructor using an array as parameter values.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = [1, 2, 3]
   
    function construct(val1, val2, val3) {
      this.val1 = val1;
      this.val2 = val2;
      this.val3 = val3;
    }
   
    function construct2(args) {
      this.val1 = args[0];
      this.val2 = args[1];
      this.val3 = args[2];
    }
   
    function construct3(args) {
      var num = 1;
      for (var val = 0; val < args.length; val++) {
        this['val' + num] = args[val];
        ++num;
      }
    }
   
    function construct4(args) {
   
    }
    construct4.prototype.fn = function(args) {
      var num = 1;
      for (var val = 0; val < args.length; val++) {
        this['val' + num] = args[val];
        ++num;
      }
    }
};
</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
Apply Method
var _1 = new construct();
construct.apply(_1, arr);
pending…
Direct Array
var _2 = new construct2(arr);
pending…
For Loop (Direct)
var _3 = new construct3(arr);
pending…
For Loop (Prototype)
var _4 = new construct4();
_4.fn(arr);
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