Get first item of set - large set with lots of different elements

Benchmark created on


Setup

const set = new Set();

set.add(new Date());

for (let i = 0; i < 100000; i++) {
	set.add(Math.random());
}

set.add(new Date());

for (let i = 0; i < 100000; i++) {
	set.add(i*10);
}
set.add(new Date());

for (let i = 0; i < 100000; i++) {
	set.add(performance.now());
}
set.add(new Date());

const alph = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const randChar = () => alph[Math.floor(Math.random()*alph.length)];
const randChars = (len = 6) => Array(len).fill(0).map(a => randChar()).join("");
for (let i = 0; i < 100000; i++) {
	set.add(randChars(Math.ceil(Math.random()*100)));
}

function getFirstItemOfSet(set) {
  for(let item of set) {
    if(item) {
       return item;
    }   
  }
  return undefined;
}

Test runner

Ready to run.

Testing in
TestOps/sec
spread
const first = [...set][0];
ready
iterator on keys
const first = set.keys().next().value;
ready
destructuring
const [first] = set;
ready
getFirstItemOfSet
const first = getFirstItemOfSet(set);
ready

Revisions

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