optimizationpremature-optimization

How to optimize a statement of the form "if (A == B) { ...} else if (A < B) {...} else { ....}"


I have a piece of code that's like

if (A == B)
{
    ...
}
else if (A < B)
{
    ... 
}
else // (A > B)
{
    ...
}

I realize there is a redundancy problem because there will be some of the same bit comparisons going into the computation of == and <. How can I optimize my code to make it fancier and faster?


Solution

  • For C# you could use a generic function that takes in the 2 values, and then a lambda action for each case.

    void CompareAndAct<T>(T a, T b, Action fnEqualTo, Action fnLessThan, Action fnGreaterThan)  {
    
       var comparison = System.Collections.Generic.Comparer<T>.Default.Compare(a, b);
       if (comparison == 0) {
          fnEqualTo();
       }
       else if (comparison < 0) {
          fnLessThan();
       }
       else {  //A > B
          fnGreaterThan();
       }
    }
    

    Then you can re-use it as much as you wanted like so:

    CompareAndAct(a,b, () => Console.Writeline("Equal"),() => Console.WriteLine("Less Than", () => Console.WriteLine("Greater Than"));
    

    I can't say I'd recommend doing this, but it'd work. It's no faster (prob slower), but I suppose one could say that it's "fancier."