Is there a proper way of clamping from 0 to infinity (max value)?

I’ve been using the follow for my code:

int score = 0;

void SetScore( int newVal )
{
       score = Mathf.Clamp( newVal, 0, int.MaxValue );
}

SetScore(-10);              // score = 0
SetScore(2147483647);       // score = 2147483647

, but I’ve always assumed that it’s inefficient.

If it is actually inefficient, please tell me the correct way of doing it. I’ve always wondered on how it is done.

Instead of using Mathf.Clamp, you can use Mathf.Max to make sure your score is always at least 0:

void SetScore( int newVal )
{
    score = Mathf.Max( 0, newVal );
}

This works, because:

Mathf.Max(0, -10) = 0
Mathf.Max(0, 2147483647) = 2147483647

Normal computer today are running with about 3 GHz and are able to process around 78.440 64bit instructions per second. The clamp function uses 2 comparisons. This is A. not optimizable. (Unless you assume, that a score of about int.MaxValue is not reachable. Then you can replace it with Mathf.Min) and B. does not affect the performence on any level. Why are you woring about this code? If you want to see the performance impact, use the profiler. But I doubt, that anything visible will appear.