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){
------------
------------
}
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)
Thank you @john001
Of course you can't use
switch
unless all the cases are constants.yes, indeed