Reputation: 4364
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?
Upvotes: 2
Views: 9817
Reputation: 41805
Math.Clamp
was introduced since .NET Core 2.0 so you can use it directly. It should be the current fastest method
Math.Clamp(12, 0, 50)
Upvotes: 1
Reputation: 91
If you want speed, you should keep the CPU's branch predictor happy. So make the "happy path" return 'n' (the most probable outcome of calling 'Clamp'):
public static int Clamp( int n, int min, int max ) {
if( value < min ) return min;
if( value > max ) return max;
return n;
}
Upvotes: 4
Reputation: 254926
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.
Upvotes: 5