Set check before add vs add

Benchmark created on


Description

Is it faster to check for an item before adding it to as set, or just add it (and it will be ignored by the set because it is already in in)

Setup

const testSet100 = new Set();
for (var i=0; i<100; i++) {
	testSet100.add(i);
}

const testSet1000 = new Set();
for (var i=0; i<1000; i++) {
	testSet1000.add(i);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Add without check (100)
for (var i=0; i<100; i++) {
	testSet100.add(i);
}
ready
Add with check (100)
for (var i=0; i<100; i++) {
	if (!testSet100.has(i)) {
		testSet100.add(i);
	}
}
ready
Add without check (1000)
for (var i=0; i<1000; i++) {
	testSet1000.add(i);
}
ready
Add with check (1000)
for (var i=0; i<1000; i++) {
	if (!testSet1000.has(i)) {
		testSet1000.add(i);
	}
}
ready

Revisions

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