Performance of Mathf.Clamp vs if-else statement?

Quick question: I’m performing a rather quick operation in Update() to keep a number from going to far in both directions. I was wondering if using Mathf.Camp() is faster then using a if() else() statement?

Here’s my code below:

// The Clamp way:
boostCharge = Mathf.Clamp(boostCharge, 0, BoostChargeFull);

// The if() else() way:
if(boostCharge < 0) boostCharge = 0;
else if(boostCharge > BoostChargeFull) boostCharge = BoostChargeFull;

As you can see, nothing special…so does it even matter for this specific case?

What do you guys think?

Thanks!

Stephane

Hey Stephane,
I suggest you download ILSpy or a similar program so you can look through Unity’s code yourself. Here’s the Mathf.Clamp function:

public static float Clamp(float value, float min, float max)
	{
		if (value < min)
		{
			value = min;
		}
		else
		{
			if (value > max)
			{
				value = max;
			}
		}
		return value;
	}