Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 692
Christian Avatar asked Sep 04 '25 17:09

Christian


1 Answers

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.

like image 68
Rajesh Avatar answered Sep 07 '25 08:09

Rajesh