DEV Community

Sadman Salim Nipun โ˜‘๏ธ
Sadman Salim Nipun โ˜‘๏ธ

Posted on

Switch Case vs. If Else: An Interesting Fact ๐Ÿ˜ฑ

Greetings! Wishing you a great day!!

While coding we generally use if-else or switch-case to work on condition checking. But do you know that although both are used for condition checking, using switch-case is more efficient than if-else?!

For switch-case, condition checking basically branch table or binary search (logarithmic time complexity) is used where for if-else, each condition is checked one by one until the condition is true.

Branch table is much like hash table. That is why when,

    switch(variable){
    ------------
    ------------
    }
Enter fullscreen mode Exit fullscreen mode

When switch is used like this, the programming control for variable is transferred directly to the case for which it is true (without checking any other cases) and the code under that case is executed. However, for a small number of condition checking, using switch-case or if-else does not change the execution time much. โฐ

But what is more important is the readability of the code. Programmers tend to encourage the use of switch-caseโœ”๏ธrather than if-else. Because code with switch-case is more comfortable to read than if-else.

Happy Coding!! ๐Ÿ‘จโ€๐Ÿ’ป


Follow me on LinkedIn

Top comments (3)

Collapse
 
nipun333 profile image
Sadman Salim Nipun โ˜‘๏ธ

Thank you @john001

Collapse
 
pauljlucas profile image
Paul J. Lucas

Of course you can't use switch unless all the cases are constants.

Collapse
 
nipun333 profile image
Sadman Salim Nipun โ˜‘๏ธ

yes, indeed