In this article I'm not going to explain the basics of switch and if else
statements. But I'm going give some points based on my experience from a
performance point of view.
When it comes to performance my rule of thumb is always measure the execution
time and decide which solution perform better rather than going with theory.
Because you might not know how the complier will optimize or based on other
factors it might not work as per the theory.
Generally switch statements are faster than if else statements. But when there
are few cases (less than 5) it is better to with if else statements as there
will no significant performance improvement. Compliers normally generates a
jump table when compiling a switch statement by looking at the cases. In worst
case complier will produce same code as if else case.
In general when coding first you should focus on the readability of the code.
If it is performance critical code we should optimize for performance. When
there are two or three cases if else statements are cleaner. Specially when
there is a boolean check if else statements perform better. But when there are
more cases if switch statements are cleaner.
When using switch statements best practice is to end a non empty case with a
break statement. Not following that may lead to issues and it will reduce the
maintainability of the code.
Now let's look at if else statements. When you use if else statements in a
performance critical code section always use the best possible condition as
the first if case and follow the order. While working I have come across
developers who do not pay attention to tiny details like these. But if you are
a good Software Engineer these things will be applied automatically when you
write code.
This point is not related to performance but anyway I thought I should
mention. When there is a single line inside if or else statement some
developers tend to use a single line as shown in below.
From my opinion this is a bad practice. Specially when the statement inside if
is a return statement. Because when you write code like this you loose the
flow of the code which affects the readability and it makes hard to debug as
you can't put a break point to that line. I hope to discuss more about these
in a separate article.
If you have any important points that should be added to this article feel
free to add those in comments. I would love to include those in the article.