thenativeweb / node-cqrs-domain

Node-cqrs-domain is a node.js module based on nodeEventStore that. It can be very useful as domain component if you work with (d)ddd, cqrs, eventdenormalizer, host, etc.
http://cqrs.js.org/pages/domain.html
MIT License
269 stars 57 forks source link

think about optimizing with immutable objects #37

Closed adrai closed 9 years ago

adrai commented 9 years ago
var _ = require('lodash');

var evt = {
  "id": "-",
  "aggregate": {
    "name": "person"
  },
  "name": "changePersonInfo",
  "context": {
    "name": "operations"
  },
  "payload": {
    "gender": "male",
    "firstName": "Rolf",
    "lastName": "Bauer",
    "info": "some string changed",
    "entryDate": "2014-10-01T16:13:39.213Z",
    "exitDate": "2014-10-06T16:13:39.213Z",
    "email": "asdf@test2.de",
    "phoneNumber": "0791231289",
    "pictureId": "C0FF33"
  },
  "meta": {
    "siteId": "someSiteId"
  }
};

var evts = [];

for (var i = 0; i < 1; i++) {
  var clonedEvt = _.cloneDeep(evt);

  clonedEvt.id = i + 1;
  evts.push(clonedEvt);
}

var cloneDeepResult = 0;
var jsonStringifyParseResult = 0;
var deepFreezeResult = 0;

var start = Date.now();
evts.forEach(function (e, i) {
  console.log(i + 1);
  _.cloneDeep(e);
});
var end = Date.now();
cloneDeepResult = end - start;

var start = Date.now();
evts.forEach(function (e, i) {
  console.log(i + 1);
  JSON.parse(JSON.stringify(e));
});
var end = Date.now();
jsonStringifyParseResult = end - start;

function deepFreeze(o) {
  var prop, propKey;
  Object.freeze(o); // First freeze the object.
  for (propKey in o) {
    prop = o[propKey];
    if (!o.hasOwnProperty(propKey) || !(typeof prop === 'object') || Object.isFrozen(prop)) {
      // If the object is on the prototype, not an object, or is already frozen,
      // skip it. Note that this might leave an unfrozen reference somewhere in the
      // object if there is an already frozen object containing an unfrozen object.
      continue;
    }

    deepFreeze(prop); // Recursively call deepFreeze.
  }
}

var start = Date.now();
evts.forEach(function (e, i) {
  console.log(i + 1);
  deepFreeze(e);
});
var end = Date.now();
deepFreezeResult = end - start;

console.log('_.cloneDeep(e);: ' + cloneDeepResult + 'ms');
console.log('JSON.parse(JSON.stringify(e)): ' + jsonStringifyParseResult + 'ms');
console.log('deepFreeze(e): ' + deepFreezeResult + 'ms');
adrai commented 9 years ago

it's not the bottleneck