+ 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?

27th Feb 2017, 5:24 AM
Kyle Allevato
Kyle Allevato - avatar
7 ответов
+ 3
switch is always faster and better practice in code as well as nested if else statements can easily become complicated.
27th Feb 2017, 5:29 AM
Andre van Rensburg
Andre van Rensburg - avatar
+ 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
7th Apr 2020, 6:41 PM
ZhangXX
ZhangXX - avatar
+ 1
switch case is faster and better
1st Mar 2017, 6:04 AM
Shekhar Dhananjay Jadhav
Shekhar Dhananjay Jadhav  - avatar
+ 1
switch is better u may confuse by nested if its better yo use switch
1st Mar 2017, 12:40 PM
smeily
+ 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.
2nd May 2017, 6:07 PM
Nicholas McClain-Simpson
Nicholas McClain-Simpson - avatar
0
I suggest 'if else' if your concept is clear!!
16th Mar 2017, 6:39 PM
Pasang Tsering
Pasang Tsering  - avatar
0
Can any body explain complexity of both please (if else and switch)
4th Aug 2019, 2:13 PM
Ganapati Marathi
Ganapati Marathi - avatar