+ 7
Switch vs If/ElseIf/Else
what is the difference of using the switch statements or if/else statements? they both kinda do the same thing...how do I choose which one to use? are there pros and cons for using each?
5 odpowiedzi
+ 11
not much difference but switch statement is faster than if else because for if else statement all the cases have to be checked which should be executed instead in switch statement it only decide which should be executed.
+ 5
Almost every post here claimed that switch statement is faster then if. Does anyone here have a solid proof code sample that can prove switch statement is faster then if?.
+ 3
Switch only accepts concrete values as cases of the variable being tested, while if-elseIf-else allows a more flexible test with comparison signs and because of that, can cover wider or complex cases.
+ 1
switch case is less code intensive and makes for faster processing of the information.
+ 1
Internally, machine code doesn't have an instruction similar to SWITCH on high level languages. The unique programmatic structure is a comparison with CMP and a conditional jump with JMP/JPZ/JPE or other, what is completely equivalent to a high level IF. SO compilers translate directly IF to machine code and SWITCH has to be firstly translated to a battery of IF's. Therefore, SWITCH IS NOT MORE QUICK THAN SWITCH. The only reason to use SWITCH is when you don't have complex cases of conditions to manage in order for you to have simplicity in code.