+ 2
In terms of time complexity what is better, switch case or if else statements?
Which (if else or switch case) statements are fastest when compiling and running the program?
7 ответов
+ 3
switch is always faster and better practice in code as well as nested if else statements can easily become complicated.
+ 2
Ganapati Marathi , it's a bit like linear and random access, in which if-else is linear access, switch is random access. For that switch will change the conditions into jump table.
"In most languages, switch only accepts primitive types as key and constants as cases. This means it can be optimized by the compiler using a jump table which is very fast." from
https://stackoverflow.com/a/680664/8025965
+ 1
switch case is faster and better
+ 1
switch is better u may confuse by nested if its better yo use switch
+ 1
It depends on the situation, Generally:
Use 'switch' when the the options are set or 'static'
Use if trees when the options can be ranged
Switch works best if you have a set number of inputs that will generate corresponding outputs. Like a menu.
If trees are more versatile for use with ranged values.
If(x > 8) {//code}
else{//other code}
This is much simpler than writing a switch for all inputs greater than 8.
0
I suggest 'if else' if your concept is clear!!
0
Can any body explain complexity of both please (if else and switch)