For vs Filter, Map

Benchmark created on


Description

Testing the performance differences between a for loop with an if condition, and filter, mapping over.

We will generate an array with a million entries that are numbers between 0 and 100. We will then ignore any number below 25, and return all numbers above.

Setup

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Create an empty array
const largeArray = [];

// Generate and push 1,000,000 random numbers into the array
for (let i = 0; i < 10000; i++) {
  const randomNumber = getRandomNumber(1, 100); // Generate a random number between 1 and 100
  largeArray.push({num, randomField: true});
}

Test runner

Ready to run.

Testing in
TestOps/sec
For Loop
const filteredNumbers = []
for (var i = 0; i <= largeArray.length; i++) {
	if (largeArray[i].num < 25) {
		continue;
	}
	
	filteredNumbers.push(largeArray[i].num)
}

console.log(filteredNumbers.length)
ready
Filter...Map
const filteredNumbers = largeArray.filter(({num}) => num >= 25).map(({num}) => num)

console.log(filteredNumbers.length)
ready

Revisions

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