Generator vs Array filtering

Benchmark created on


Description

Which is faster? Array.filter or for..of..if

Setup

let counter = 0;
const largeData = Array.from({ length: 10_000 }, () => counter++);
const largeDataSet = new Set(largeData);

const isEven = (num) => num % 2 === 0; 

function arrayTest(data) {
	return data.filter(isEven);
}

function *generatorTest(data) {
	for (let num of data)
	  if (isEven(num)) yield num;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Array.filter with array
let result = arrayTest(largeData);
ready
Generator with array
let result = Array.from(generatorTest(largeData));
ready
Array.filter with set
let result = arrayTest(Array.from(largeDataSet));
ready
Generator with set
let result = Array.from(generatorTest(largeDataSet));
ready

Revisions

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