For vs Filter, Map (v3)

Revision 3 of this 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 10,000 random numbers into the array
for (let i = 0; i < 1000000; i++) {
  const num = 75; // 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 (let i = 0; i < largeArray.length; i++) {
  if (largeArray[i].num >= 25) {
  	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.