Search code examples
c#clamp

Fastest Way To Clamp an Integer


I am not sure if "clamping" is the correct terminology for this, however I really don't know what else to call it. Suppose we wanted to limit an integer to stay within some arbitrary range, like 0-50. This can be easily achieved by testing the current value with an if statement and assigning the maximum or minimum value accordingly. However, what is the fastest way to keep the Integer at its maximum value or minimum value?


Solution

  • As easy as

    var normalized = Math.Min(50, Math.Max(0, value));
    

    As of performance:

      public static int Max(int val1, int val2) {
        return (val1>=val2)?val1:val2;
      }
    

    That's how it's implemented in .NET, so it's unlikely you can implement it even better.