for loop vs. forEach

Benchmark created on


Setup

let options = ["id","class","pseudo","tag","attribute"];
function makeItem() {
	return {
		type: options[Math.floor(Math.random() * 4.99999)]
		};
}

let smallInput = (new Array(10)).fill().map(makeItem);
let largeInput = (new Array(40000)).fill().map(makeItem);

function sortForEach(selectors) {
	let sorted = { tag: [], id: [], class: [], attribute: [], pseudo: [] };
	
	selectors.forEach((selector, i) => {
		sorted[selector.type].push(i);
	});

	return [ ... sorted.pseudo, ... sorted.tag, ... sorted.attribute, ... sorted.class, ... sorted.id ];
}

function sortFor(selectors) {
	let sorted = { tag: [], id: [], class: [], attribute: [], pseudo: [] };
	
	for (let i = 0; i < selectors.length; i++) {
		sorted[selectors[i].type].push(i);
	}

	return [ ... sorted.pseudo, ... sorted.tag, ... sorted.attribute, ... sorted.class, ... sorted.id ];
}

Test runner

Ready to run.

Testing in
TestOps/sec
forEach (small)
let sorted = sortForEach(smallInput);
ready
for loop (small)
let sorted = sortFor(smallInput);
ready
forEach (large)
let sorted = sortForEach(largeInput);
ready
for loop (large)
let sorted = sortFor(largeInput);
ready

Revisions

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