assign vs setting prototype

Benchmark created by Ian MacLeod on


Setup

var entities = [];
  for (var i = 0; i < 10000; i++) {
    entities.push({
      id: Math.round(Math.random() * 10000000),
      foo: 'abc',
      bar: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam non libero at magna viverra tincidunt fringilla ut ante.',
      baz: 1234,
      fizz: true,
      buzz: false,
      stuff: 1234,
      things: ['thing1', 'thing2', 'thing3', 'thing4', 'thing5'],
      quxes: [
        { id: 1, name: 'one' },
        { id: 2, name: 'two' },
        { id: 3, name: 'three' },
        { id: 4, name: 'four' },
      ],
    });
  }
  
  class AssignedModel {
    constructor(properties) {
      Object.assign(this, properties);
    }
  
    about() {
      return this.id;
    }
  }
  
  class SubsumedModel {
    static toModel(entity) {
      Object.setPrototypeOf(entity, this.prototype);
      return entity;
    }
  
    about() {
      return this.id;
    }
  }

Test runner

Ready to run.

Testing in
TestOps/sec
Object.assign
var models = entities.map(e => new AssignedModel(e));
var ids = models.map(m => m.about());
ready
Object.setPrototypeOf
var models = entities.map(e => SubsumedModel.toModel(e));
var ids = models.map(m => m.about());
ready

Revisions

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

  • Revision 1: published by Ian MacLeod on