When to use set in javaScript

You will find more details and browser compatibility on MDN - Set. For implementation of a Set in general, you can read Set - Implementations on Wikipedia.

Implementations described as "general use" typically strive to optimize the element_of, add, and delete operations.

You can also check some test results on the Array vs Set asnwer on Stack Overflow.


To answer your question, although the has operation might be a bit faster than using String's indexOf (or includes), in your specific case the cost of instantiating a new Set for each comparison is much greater.

I created a simple test with the following two methods:

function existsSet(str1, str2) {
  const set = new Set(str1);
  return ![...str2].some(char => !set.has(char));
}

function existsString(str1, str2) {
  return ![...str2].some(char => !str1.includes(char));
}

I called the above methods for 1 million randomly created strings and I got the following results:

existsSet: 1.29s
existsString: 0.47s

That's almost three times slower for the method that instantiates a Set.


You can find the test I run on the following JsFiddle:

https://jsfiddle.net/mspyratos/zwx3zcx1/11/