Optimizing nested if statements in switch I have this code and I think it is very slow, about 50ms. I need to make it execute faster:

 switch (unit)
   {
       case 0:
       if (u == 2)
       {
           if (u1 == "piece" || u1 == "gram")
               result = quantity * y;
           else
               result = quantity * z;
       }
       if (u == 1)
       {
           if (u1 == "piece" || u1 == "gram")
               result = quantity * y;
           else
               result = quantity;
       }
       res_name = "gram";
       break;

       case 1: //ml
       if (u == 2)
       {
           if (u1 == "piece" || u1 == "gram")
               result = quantity * x;
           else
               result = quantity * y;

       }
       if (u == 0)
       {
           if (u1 == "piece" || u1 == "gram")
               result  = quantity * x;
           else
               result = quantity;
       }
       res_u = "ml";
       break;

case 2:
    res_u = "pieces";
    break;
 }
I agree with Romoku.  Unless there is a definite requirement to make this faster and a noticeable effect on performance of your application within this method I would consider making it more DRY, more developer friendly and less procedural.

Without more code and explanation of whats there here are some things I would consider:


Try and remove duplicated code.  I notice you repeat your if(u1 == "piece" ... code everywhere.  Consider moving that into a method and passing in the parameters required.  

private int GetConversion(UnitsEnum units, int pieceGramsMultipler, int otherMultipler)
{
  return units == UnitsEnum.Piece || units == UnitsEnum.Gram
                 ? pieceGramsMultipler
                 : otherMultipler;               
}


Then used like

if (u == 2)
{
   result = quantity * GetConversion(u1, y, z);                        
}

Consider changing your string literals into enumerations. So "piece" and "gram" might become:

private enum UnitsEnum
{
  Piece,
  Gram
}

Consider changing your case statements into constants or enumerations.  So rather than case 1, it might be case Metric.Ml or ML or Milliliters etc
Offer better names for your variables.  u1, x, y, z gives me no idea of what they are trying to do.  
Use if else instead of 2 if statements.  If u == 2 then there is no chance that it will be == 1 so convert your if's into if elses to make that more obvious.


Otherwise, perhaps posting the full code that this piece resides in might get your more help and suggestions.  I get the feeling that there is more help this community can offer you here than just what you have posted.