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

Revision 108 of this benchmark created on


Description

use random, slightly more realistic data

Preparation HTML

<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);
  };

  wrapper2 = function(opts) {
    var o = {
    x : opts.x,
    y : opts.y,
    z : opts.z,
    s : opts.s
    };
    return o;
  };

  Obj.prototype.create = function(opts) {
    return new Obj(opts);
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/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
    }
  });
}
ready
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);
}
ready
Constructor function
for (var i = 0; i < data.length; ++i) {
  var o = new Obj(data[i]);
}
ready
Constructor wrapper
for (var i = 0; i < data.length; ++i) {
  var o = wrapper(data[i]);
}
ready
Prototype pattern with constructor wrapper
for (var i = 0; i < data.length; ++i) {
  var o = Obj.prototype.create(data[i]);
}
ready
Constructor wrapper2 with literal
for (var i = 0; i < data.length; ++i) {
  var o = wrapper2(data[i]);
}
ready

Revisions

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