DEV Community


Discussion on: A Case Against Switches

darkain profile image
Vincent Milum Jr

I can understand this from a JavaScript perspective, but this technique is very language specific. One of the HUGE reasons why switch statements exist in the first place is due to the way C/C++ compilers can optimize them behind the scenes. They're significantly faster to process if done correctly, because the compiler will build a jump table rather than a series of comparisons. In modern programming where we're just basically doing glue layers and performance isn't as critical, it doesn't matter much, but when you're working with microcontrollers or doing hardware drivers, it makes a world of difference.

Another advantage of switch statements is that some languages will allow for backwards comparisons. You can do something like "switch (true)" and then run a ton of cases to see which one is true first, and then process accordingly.

jckuhl profile image
Jonathan Kuhl Author

Sure, if the language you're working in has a lot of optimization for switches, then go with what works best for the language. My post was indeed mostly centered around JS. I know little about C++, so I won't presume to speak on it. If switches are better in C/C++, stick with them.

And even in JavaScript, if the situation is such that a switch is the simplest and most efficient way to achieve what you're looking for, then I'd remain with the structure.