Object.entries() iteration / allocation overhead (v5)

Revision 5 of this benchmark created on


Setup

const testA = {
	    name: "John",
    	age: 30
    };
    
const testB = {
    	name: "Maria",
    	age: 31
    };
    
const testC = {
		    name: "Sandra",
 	   		age: 6
		};
		
const testD = {
		    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
let newValue;

for (let i = 0; i < 10000; i ++) {
  test(testA);
  test(testB);
  test(testC);
  test(testD);
}

function test (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
let newValue;

for (let i = 0; i < 10000; i ++) {
  test(testA);
  test(testB);
  test(testC);
  test(testD);
}

function test (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
let newValue;

for (let i = 0; i < 10000; i ++) {
  test(testA);
  test(testB);
  test(testC);
  test(testD);
}

function test (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
let newValue;

for (let i = 0; i < 10000; i ++) {
  test(testA);
  test(testB);
  test(testC);
  test(testD);
}

function test (value) {
	
  constraintsMap.forEach((excludedValue, excludedKey) => {
    if (value[excludedKey] && value[excludedKey] === excludedValue) {
      newValue = {};
      
      for (const topLevelKey in value) {
      	if (value.hasOwnProperty(topLevelKey)) {
      	  newValue[topLevelKey] = 'foo';
      	}
      }

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

Revisions

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