Concat v Push 4

Benchmark created on


Setup

class Model {
  constructor(id, type, childIds = []) {
    this.id = id;
    this.type = type;
    this.childIds = childIds;
  }
}

class Store {
  constructor() {
    this._nodes = {};
  }

  getModel(id) {
    return this._nodes[id] || new Model("", "");
  }

  addModel(model) {
    this._nodes[model.id] = model;
  }

  getModelByTypeConcat(type, params) {
    const { startId = "1", limit = 1, depth = 1 } = params;
    const model = this.getModel(startId);

    let result = [];

    if (depth <= 0 || limit <= 0) {
      return result;
    }

    if (model.type === type) {
      result.push(model);
    }

    const childIds = model.childIds ?? [];

    for (const childId of childIds) {
      result = result.concat(
        this.getModelByTypeConcat(type, {
          depth: depth - 1,
          limit: limit - result.length,
          startId: childId,
        })
      );

      if (result.length >= limit) {
        break;
      }
    }
    return result;
  }

  getModelByTypePush(type, params) {
    const { startId = "1", limit = 1, depth = 1 } = params;
    const model = this.getModel(startId);

    let result = [];

    if (depth <= 0 || limit <= 0) {
      return result;
    }

    if (model.type === type) {
      result.push(model);
    }

    const childIds = model.childIds ?? [];

    for (const childId of childIds) {
      result.push(
        ...this.getModelByTypePush(type, {
          depth: depth - 1,
          limit: limit - result.length,
          startId: childId,
        })
      );

      if (result.length >= limit) {
        break;
      }
    }
    return result;
  }
}

// Example
const store = new Store();

const model1 = new Model("1", "circle");
const model2 = new Model("2", "square");
const model3 = new Model("3", "triangle");
const model4 = new Model("4", "circle");
const model5 = new Model("5", "circle");
const model6 = new Model("6", "square");
const model7 = new Model("7", "square");
const model8 = new Model("8", "square");
const model9 = new Model("9", "square");

model1.childIds = ["2", "3"];
model2.childIds = ["4"];
model3.childIds = ["5"];
model5.childIds = ["6", "7"];
model7.childIds = ["8", "9"];

store.addModel(model1);
store.addModel(model2);
store.addModel(model3);
store.addModel(model4);
store.addModel(model5);
store.addModel(model6);
store.addModel(model7);
store.addModel(model8);
store.addModel(model9);

Test runner

Ready to run.

Testing in
TestOps/sec
Concat
store.getModelByTypeConcat("square", { limit: 10, depth: 10 });
ready
Push
store.getModelByTypePush("square", { limit: 10, depth: 10 });
ready

Revisions

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