switch and if else efficiency

switch case 与 if else

  1. a switch case jump table is generated to indicate the actual address of the branch case, the branch table index number is equal to the value of the switch variable. And if else is needed in order to traverse conditions until conditions are met.
The advantages and disadvantages of the switch case

Advantage :
in terms of efficiency: when a large branch, switch efficiency is very high. Because swtich After determining the selected value, will jump directly to that particular branch.
Disadvantages :

  1. switch case take up more space code, because he wanted to generate a jump table, especially when the case of a constant distribution case, but in fact a lot less effective case, the efficiency of the switch becomes very low.
  2. switch case can only deal with the case as the case constants, such as the code below:
switch(a)
{
	case 100:
	   //...
	   break;
}
//无法支持 下方代码
if(a > 10 && a < 100);
if else advantages and disadvantages

Advantage : if else can be used in more scenes, more flexible.
Disadvantage : the order must be traversed if else;
of course, both may also be used in conjunction, switch nested if else.

to sum up

Please branches in more cases, use switch case structure will enhance the efficiency of the program, but the inadequacies of switch that can handle character and numeric variables.
if else is relatively flexible and can be configured to determine whether any of the established expression, more or less complex if else branch judgment statement used.

Published 52 original articles · won praise 26 · views 3388

Guess you like

Origin blog.csdn.net/weixin_43796685/article/details/104839546