Object.entries() iteration / allocation overhead

Benchmark created on


Setup

const objectToSerialize = {
	father: {
	    name: "John",
    	age: 30
    },
    mother: {
    	name: "Maria",
    	age: 31
    },
    children: [
		{
		    name: "Sandra",
 	   		age: 6
		}, {
		    name: "Jake",
 	   		age: 4
		}
    ]
};

const constraints = {
    name: "Maria"
};

const constraintsEntries = Object.entries(constraints);
const constraintsMap = new Map(constraintsEntries);

Test runner

Ready to run.

Testing in
TestOps/sec
Object.entries() in loop
JSON.stringify(objectToSerialize, (key, value) => {
  Object.entries(constraints).forEach(([excludedKey, excludedValue]) => {
    if (value[excludedKey] && value[excludedKey] === excludedValue) {
      newValue = {};
      
      Object.keys(value).forEach(topLevelKey => {
        newValue[topLevelKey] = 'foo';
      });

      newValue[excludedKey] = excludedValue;
    }
  });	
});
ready
Object.entries() outside loop
JSON.stringify(objectToSerialize, (key, value) => {
  constraintsEntries.forEach(([excludedKey, excludedValue]) => {
    if (value[excludedKey] && value[excludedKey] === excludedValue) {
      newValue = {};
      
      Object.keys(value).forEach(topLevelKey => {
        newValue[topLevelKey] = 'foo';
      });

      newValue[excludedKey] = excludedValue;
    }
  });	
});
ready
Map outside loop
JSON.stringify(objectToSerialize, (key, value) => {
  constraintsMap.forEach((excludedValue, excludedKey) => {
    if (value[excludedKey] && value[excludedKey] === excludedValue) {
      newValue = {};
      
      Object.keys(value).forEach(topLevelKey => {
        newValue[topLevelKey] = 'foo';
      });

      newValue[excludedKey] = excludedValue;
    }
  });	
});
ready
Allocation-free
JSON.stringify(objectToSerialize, (key, value) => {
  constraintsMap.forEach((excludedValue, excludedKey) => {
    if (value[excludedKey] && value[excludedKey] === excludedValue) {
      newValue = {};
      
      for (const topLevelKey in value) {
      	if (value.hasOwnProperty(topLevelKey)) {
      	  newValue[property] = 'foo';
      	}
      }

      newValue[excludedKey] = excludedValue;
    }
  });	
});
ready

Revisions

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