DEV Community

Discussion on: Stop using if else

Collapse
 
d3sox profile image
Nico

I agree with what @bubster said. You should rename it to "stop abusing".

Plus I did some benchmarking. It seems like if/else is always the slowest, using a Map makes only a negligible difference in Firefox, and an object is much faster in Chrome. Test for yourself: jsbench.me/jekur7m830/1

(I modified your code a little bit to keep things fair. You called toLowerCase for every branch in the first example and didn't use it in the latter two. I also moved the declaration of the object/Map out of the function, otherwise it would be created for every iteration)

When adding more calls like

whoIsThis('naruto')
whoIsThis('')
Enter fullscreen mode Exit fullscreen mode

to each test case if/else actually wins in Chrome which makes me think if Chrome somehow caches it.

Collapse
 
rjitsu profile image
Rishav Jadon

Oh my bad for not using toLowerCase in further examples! Thanks for the tip about moving the dictionary out of the function.

Collapse
 
bk profile image
BK ☕

You agreed with the tip, but the code example is still not updated. It's better to make the change, so beginners can learn from better examples.

Collapse
 
bk profile image
BK ☕

Btw, my other comment was referring to "Thanks for the tip about moving the dictionary out of the function."

Have a lovely day.

Collapse
 
michaelcurrin profile image
Michael Currin

At large scale a lookup by key is far more efficient. At small scale it is maybe small difference.

If you had extreme case of code of say 1000 branches of if else statements, at worst it takes 1000 attempts until the last one matches.

While looking up a value from an object/map by key is constant - only needed exactly one attempt to find the result.

Some comments have been hidden by the post's author - find out more