+ 2
What are the three major differences in between if-else and switch statement?
2 Réponses
+ 3
In a switch statement if you don’t use break statements for each case, each case without the break will run. The switch also takes values where ifs evaluate if the statement you provided is true or false. An if-else evaulates at an hierarchal order checking from the first is statement to the last. They do not need break statements because if its true the rest of the else if statements won’t be evaluated.
+ 2
Something major is that a switch statement uses a jump table.
If you have a huge amount of if, else if, and else statements then the program will have to check every single statement sequentially, and worst case is that the condition is the last one and it'll have to check every single statement, and the best case is that the first one is true.
For a switch statement however, the program will know exactly where to go and will jump directly to the case, not having to check the other cases, saving time when dealing with a larger amount of conditions.
Albeit, most computers are fast enough where you don't really see a difference, but it does exist.