- Home /
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
Answer by Julien-Lynge · May 20, 2013 at 06:55 AM
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;
}
Hi Julien, thanks for the tip, I'll look into it for sure! So basically the Clamp function does exactly what I wanted to do with my if() else() block...saves me the trouble hahaha :)
Thanks again!
ILspy sounds awesome, do you mean it would be possible to see the source of something like -recalculate normals- ? it would be great for multithreading reasons.
ILSpy allows you to look through dlls, for instance UnityEngine.dll. However, you'll definitely find that there are limitations, and RecalculateNormals is one of those. $$anonymous$$any methods are implemented in internal libraries outside the dll, and sadly those are much harder to peruse. Here's a bit more info:
http://answers.unity3d.com/questions/440089/where-does-extern-point-in-unityenginedll-methods.html
Your answer
Follow this Question
Related Questions
Implementing mathf ? 1 Answer
Modify distance with var? 1 Answer
limit accelerometer controlled rotation 1 Answer
How do I change a spot light to a point light by pressing a key? 1 Answer
How do I find the inverse cosine ??? 1 Answer