New Set Vs ForEach set.add()

Benchmark created on


Description

I want to understand the difference between

new Set(arrayOfItems.map(item => item.id))

and

const theSet = new Set(); arrayOfItems.forEach(item => theSet.add(item.id));

Constraints: All items will have an ID - no benefit from filtering first. Ids can be duplicates (hence the need for a set)

Setup

const arrayOfItems = new Array(100_000);

function randomizeArrayIds(array) {
    for (var i = array.length - 1; i > 0; i--) {
		array[i] = { id: Math.floor(Math.random() * 1000) };
    }
}

randomizeArrayIds(arrayOfItems);

Test runner

Ready to run.

Testing in
TestOps/sec
new Set(arrayOfItems.map(item => item.id));
new Set(arrayOfItems.map(item => item.id));
ready
arrayOfItems.forEach(item => theSet.add(item.id));
const theSet = new Set();
arrayOfItems.forEach(item => theSet.add(item.id));
ready

Revisions

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