-1

When checking a short list of variables for being within a set, what structure is most efficient.

if(checkString === 'string1'
  || checkString === 'someString2'
  || checkString === 'differentString3'
  || checkString === 'lol'
  || checkString === 'jsIsFun'
){doThing();}

For readability I would prefer one of the following:

if(['string1', 'string2','differentString3', 'lol', 'jsIsFun'].includes(checkString)){
  doThing();
}

or:

switch (checkString) {
  case 'string1':
  case 'string2':
  case 'differentString3':
  case 'lol':
  case 'jsIsFun':
    doThing();
    break;
}

For a touch of background, I am trying to tidy chains of if-else with a similar structure to the first example. The checkString has a relatively even distribution of items it would expect to match in the set.

The structure of the data is not already in an array, so I am wondering if there is any meaningful memory cost to initializing an array for using 'includes'.

Is one of the above methods the most efficient for vanilla JS, or is there a better way to check for string belonging to a state.

Aaron Morefield
  • 952
  • 10
  • 18

1 Answers1

2

Theoretically, there must be a difference in efficiency between the 3 options you listed (all done in linear time), and an object lookup (constant time) like you see below:

const checkObject = {
    'string1': true,
    'string2': true,
    'differentString3': true,
    'lol': true,
    'jsIsFun': true,
}

if (checkObject[checkString]) doThing()

or

const checkSet = new Set(['string1', 'string2', 'differentString3', 'lol', 'jsIsFun'])

if (checkSet.has(checkString)) doThing();

*if we do not count the time spent on initiating the checkObject and checkSet

You can read more about it in this question, and check out this benchmark comparison between an array includes, object, and set (the set is quite a bit faster than array.includes).

However, this won't make a significant difference for a small array, so it's really a matter of taste.

Dorin Botan
  • 1,224
  • 8
  • 19