Object.create() vs. constructor vs. object literal

JavaScript performance comparison

Revision 105 of this test case created by Ryan Lauck

Info

use random, slightly more realistic data

Preparation code

<script>
  data = [];
  for(var i = 0; i < 1000; i++){
    data[i] = {
      x: Math.random(),
      y: Math.random(),
      z: Math.random(),
      s: "str-"+Math.random()
    };
  }

  Obj = function(opts) {
    this.x = opts.x;
    this.y = opts.y;
    this.z = opts.z;
    this.s = opts.s;
  };

  wrapper = function(opts) {
    return new Obj(opts);
  };

  Obj.prototype.create = function(opts) {
    return new Obj(opts);
  };
</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
Object.create() using in-place property object
for(var i = 0; i < data.length; ++i){
  var opts = data[i];
  var o = Object.create(Object.prototype, {
    x: { value: opts.x },
    y: { value: opts.y },
    z: { value: opts.z },
    s: { value: opts.s }
  });
}
pending…
Object.create() using constant property object
var propObj = {
  x: { value: data[0].x },
  y: { value: data[0].y },
  z: { value: data[0].z },
  s: { value: data[0].s }
}
for(var i = 0; i < data.length; ++i){
  var o = Object.create(Object.prototype, propObj);
}
pending…
Constructor function
for(var i = 0; i < data.length; ++i){
  var o = new Obj(data[i]);
}
pending…
Constructor wrapper
for(var i = 0; i < data.length; ++i){
  var o = wrapper(data[i]);
}
pending…
Prototype pattern with constructor wrapper
for(var i = 0; i < data.length; ++i){
  var o = Obj.prototype.create(data[i]);
}
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