A.7.5 Branch

When comparison is performed in order beginning at the top, such as in an else if statement, the execution speed in the cases at the end gets slow if there is many branching. Cases with frequent branching should be placed near the beginning.

[Example]

The return value changes depending on the value of the argument.

Source code before improvement

int func(int a)
{
     if (a==1)
          a = 2;
     else if (a==2)
          a = 4;
     else if (a==3)
          a = 0;
     else
          a = 0;
     return(a);
}

 

Assembly-language expansion code before improvement

_func: 
     CMP #01H,R1
     BEQ L11
L12:
     CMP #02H,R1
     BNE L14
L13:
     MOV.L #00000004H,R1
     RTS
L14:
     CMP #03,R1
     BNE L17
L16:
     MOV.L #00000008H,R1
     RTS
L17:
     MOV.L #00000000H,R1
     RTS
L11:
     MOV.L #00000002H,R1
     RTS

 

Source code after improvement

int func(int a)
{
     if (a==3)
          a = 8;
     else if (a==2)
          a = 4;
     else if (a==1)
          a = 2;
     else
          a = 0;
     return (a);
}

 

Assembly-language expansion code after improvement

_func:
     CMP #03H,R1
     BEQ L11
L12:
     CMP #02H,R1
     BNE L14
L13:
     MOV.L #00000004H,R1
     RTS
L14:
     CMP #01H,R1
     NE L17
L16:
     MOV.L #00000002H,R1
     RTS
L17:
     MOV.L #00000000H,R1
     RTS
L11:
     MOV.L #00000008H,R1
     RTS