Set vs foreach for unique

Benchmark created on


Setup

let messages = []

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

for(var i = 0; i < 10000; i++) {
	messages.push(randomIntFromInterval(1, 10000))
}

Test runner

Ready to run.

Testing in
TestOps/sec
foreach
let unique = []

messages.forEach((m) => {
	if(!unique.includes(m)) {
		unique.push(m)
	}
})

console.log('+-+ unique.length: ', unique.length)
ready
Set
let unique = [...new Set(messages)]

console.log('+-+ unique.length: ', unique.length)
ready

Revisions

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