Object construction

Benchmark created on


Description

Tests which way of constructing objects is faster

Setup

class PredefinedProperties {
  foo;
  bar;
  baz;
  constructor(foo, bar, baz) {
    this.foo = foo;
    this.bar = bar;
    this.baz = baz;
  }
}

class OnlyConstructor {
  constructor(foo, bar, baz) {
    this.foo = foo;
    this.bar = bar;
    this.baz = baz;
  }
}

let samples = [];
for(let i = 0; i < 1000; ++i){
  samples.push([~~(Math.random() * 100), ~~(Math.random() * 100), ~~(Math.random() * 100)]);
}
let obj;

Test runner

Ready to run.

Testing in
TestOps/sec
Class with properties
for (let i = 0; i < samples.length; ++i) {
  const sample = samples[i];
  obj = new PredefinedProperties(sample[0], sample[1], sample[2]);
}
ready
Empty class
for (let i = 0; i < samples.length; ++i) {
  const sample = samples[i];
  obj = new OnlyConstructor(sample[0], sample[1], sample[2]);
}
ready
Object at once
for (let i = 0; i < samples.length; ++i) {
  const sample = samples[i];
  obj = {foo: sample[0], bar: sample[1], baz: sample[2]};
}
ready
Object incrementally
for (let i = 0; i < samples.length; ++i) {
  const sample = samples[i];
  obj = {};
  obj.foo = sample[0];
  obj.bar = sample[1];
  obj.baz = sample[2];
}
ready

Revisions

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