Friday, September 4, 2015

switch vs if

if the cases of switch are consecutive numbers, then switch may be more optimized than if

Example:

If worst case--> 4 comparison

If (x == 1){
    body 1;
else if (x == 2){
    body 2;
else if(x == 3){
    body 3;

else if(x == 4){
    body 4;
}

Assembly:

beq x,1,L1
beq x,2,L2
beq x,3,L3
beq x,4,L4
...
...
...
L1:
Body 1

L2:
Body 2

L3:
Body 3

L4:
Body 4




switch worst case --> 1 comparison

switch (x){
    case 1: 
        body1;
        break;
    case 2: 
        body2;
        break;    case 3: 
        body3;
        break;    case 4: 
        body4;
        break;}

Assembly:

jumpIfLessThan x,4,switch+x-1
...
...
...
switch:
    L1
    L2
    L3
    L4

...
...
...
L1:
Body 1

L2:
Body 2

L3:
Body 3

L4:
Body 4


Modern compilers output the same assembly for both switch and if



Another Example:


If – else à Assembly
if (x == y)
{
   z = 1;
}else{
   z = 0;
}

      MOVE _x, R7
      COMPARE _y, R7
      BRANCH_IF_NOT_EQUAL L1
      MOVE #1, _z
      BRANCH_ALWAYS L2
 L1 MOVE #0, _z
 L2 . . .

Switch Case à Assembly
As the if – else, but in case the case values are in narrow range:
switch (num) {
case 3:
    . . .
    break;
case 4:
   . . .
   break;
case 5:
   . . .
   break;
case 6:
   . . .
   break;
}
             
// The cases labels
CASE3_LABEL  . . .
             BRANCH_ALWAYS BEYOND
CASE4_LABEL  . . .
             BRANCH_ALWAYS BEYOND
CASE5_LABEL  . . .
             BRANCH_ALWAYS BEYOND
CASE6_LABEL  . . .
             BRANCH_ALWAYS BEYOND
// Jump table
CASE_JUMP   DATA CASE3_LABEL
                                    DATA CASE4_LABEL
                                    DATA CASE5_LABEL
                                    DATA CASE6_LABEL
// When the switch case is called:
BRANCH_ALWAYS SWITCH_START
SWITCH_START        MOVE _num, R7         // R7 = num
                                                ADD #-3, R7               // R7 = num – 3 (get the jump table index)
                                                MOVE CASE_JUMP, R0          // Put the address of jump table in R0
                                                LEFT_SHIFT #2, R7 
// R7 = 4*R7 (as each entry in the jump table is 32 bit address)
                                                JUMP (R0, R7)            // jmp (base address, offset)

BEYOND       . . .

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete