mercredi 1 juillet 2015

If conditional tree to switch statement efficiency troubles

I've been trying to optimize functions with long series of if statements. I'd though I'd found a solution using switch statements as a replacement, but upon testing and disassembly, I found out that they just complicated the matter. Heres some code to demonstrate;

 int ifFunc(int A, int B, int C){
   int ret;
   if (A > 0){
     if (B > 0){
       if (C > 0){
         ret = C;
       }
       else{
         ret = B;
       }
     }
     else{
       if(C > 0){
         ret = C;
       }
       else{
         ret = A;
       }
     }
   }
   else{
     if (B > 0){
       if (C > 0){
         ret = C;
       }
       else{
         ret = B;
       }
     }
     else{
       if (C > 0){
         ret = C;
       }
       else{
         ret = 0;
       }
     }
   }
   return ret;
 }

 int swFunc(int A, int B, int C){
   int ret; int code = 0;
   code += (A > 0) * 4, code += (B > 0) * 2, code += (C > 0) * 1;
   switch(code){
   case 0: // 000
     ret = 0;
     break;
   case 1: // 001
     ret = C;
     break;
   case 2: // 010
     ret = B;
     break;
   case 3: // 011
     ret = C;
     break;
   case 4: // 100
     ret = A;
     break;
   case 5: // 101
     ret = C;
     break;
   case 6: // 110
     ret = B;
     break;
   case 7: // 111
     ret = C;
     break;
   }
   return ret;
 }
 // All these functions do is select a number that is positive,
 // Giving preference to C, then B, then A

I may have made a few mistakes, so they might not be doing exactly the same thing, but that's beside the point. What I was trying to do with the switch statement was create a version of ifFunc with only a single jump, by converting the result of each if statement into a numerical code that would align with a bit, so that each possible end point would have a unique numerical code.

This falls flat however, as the comparison functions (B > 0) etc. internally utilize jumps. It ends up with the switch version of the function being an order of magnitude slower then the if version.

I'd like to know if there is anyway to do a comparison statement, and have it output a zero for false and a one for true, without using (internally or otherwise) an if statement or a jump.

Aucun commentaire:

Enregistrer un commentaire