Tuesday, September 27, 2011

Clamping Efficiency

Been poking around the XNA 4.0 framework, trying to figure out it all works together.
(I finally realized that Vector3 themselves are not absolute positions in a 3D spatial volume, but rather relative values until Transformed to absolutes. Right?)

I came across this line of code in an example: turnAmount = MathHelper.Clamp( turnAmount, -1, 1 );
So I dug into the Clamp function.

What I saw was this:
public static float Clamp(float value, float min, float max) {
      value = (double) value > (double) max ? max : value;
      value = (double) value < (double) min ? min : value;
      return value;
    }

Isn't this function possibly inefficient? First of all, it is casting the floats to doubles.
Why? Does the compiler ignore this 'feature' and optimize it away?

And also, if the value is between the min and max, it ends up setting the value to value.
Why? Does the compiler ignore this 'feature' and optimize it away?

I would change this Clamp function to this:
public static float Clamp( float value, float min, float max ) {
            return value > max ? max : ( value < min ? min : value );
        }

If these functions are used even once per Game.Update(), and that Game.Update is called at 60 times per second.. and each Model might use it..

I'm sure the efficiency could add up to a better performing game.

No comments: