Christian
Christian

Reputation: 888

Has array.includes negative impact on performance compared to multiple if statements?

I have gotten into the habit of using Array.includes as a replacement for longer if statements.

e.g.

let varibale = 'a';
if ['b', 'c', 'd'].includes(variable) ...

instead of

let varibale = 'a';
if variable === 'b' || variable === 'c' || variable === 'd' ...

I wonder if this has a notable negative impact on performance or any other technical drawbacks?

Upvotes: 3

Views: 1040

Answers (1)

Rajesh
Rajesh

Reputation: 24945

Array.includes will always be slower but not by much.

That is because, you have some variable and using them you will create a dynamic variable which is an array. Then internally it'll loop and do lookup to test.

However, the GAIN is miniscule and will hardly matter:

Following is the JSPerf link.


So what to use, my suggestion is to use Array.includes. Yes, it slower but its maintainable and easy to read. Most of the bundler like webpack or gulp, do internal optimizations but what is important is the readability. If a developer has to invest a min to understand the code, its waste of time you'll hardly gain in performance. Plus humans would be the one to interact most with code, so my suggestion is to have readaility.

Upvotes: 5

Related Questions