For starters, case 1000 ... 1500
isn't valid C++ syntax. If you mean you want to list every individual case
between 1000 and 1500, let me tell you it is a bad idea. The most important thing about code is its readability and having 500 consecutive cases is very much the opposite of clean code.
Another thing you should also know is that switch
and if
statements are not equivalent as to what they are compiled into. if
and if else
are compiled into simple conditional jumps, while switch
is often compiled into lookup table, where value of individual cases is used as an offset for table of addresses and based on that your code will do unconditional jump to corresponding section of code. This is not the guarantee behavior and won't be the case if you have random values for cases, but in right condition (e.g. enums
) it has potential to be compiled as lookup. The final result is that for good cases you have no branches (except for range check) and your code will execute a little bit faster.
Keep in mind though that modern hardware is super fast and you simply won't notice the difference between switch
and if
unless it is in your hot path
and even then a single cache miss will be more impactful. For that very reason you should always focus on writing code that is easy to understand and makes the most sense. As for compilation, again, it's the "price" you pay once and as such should not concern you at all. My educated guess for compilation time difference between switch
and if
is that switch
would be a tiny bit slower, but you won't notice it anyway.