# Unity C# Mathf.Abs()取绝对值性能测试

``````Mathf.Abs(v)
v = v < 0 ? -v : v
if (v < 0) v = -v
// 这三种取绝对值写法中 if判断负数 效率最高``````

``````    // times = 100000000
// 1亿次 ( >=0时 2980ms) ( <0时 2993ms)
private void AbsTest0(float v) {
watch.Reset();
watch.Start();
for (int i = 0; i < times; i++) {
float f = v;
f = Mathf.Abs(f);
}
watch.Stop();
Log("AbsTest0 Mathf.Abs(f):" + watch.ElapsedMilliseconds + "ms");
}

// 1亿次 ( >=0时 1123ms 比1快165.4%) ( <0时 1153ms 比1快159.6%)
private void AbsTest1(float v) {
watch.Reset();
watch.Start();
for (int i = 0; i < times; i++) {
float f = v;
f = f < 0 ? -f : f;
}
watch.Stop();
Log("AbsTest1 三目运算:" + watch.ElapsedMilliseconds + "ms");
}

// 1亿次 ( >= 0时 950ms 18.2%) ( <0时 1094ms 比1快5.4%)
private void AbsTest2(float v) {
watch.Reset();
watch.Start();
for (int i = 0; i < times; i++) {
float f = v;
if (f < 0) f = -f;
}
watch.Stop();
Log("AbsTest2 if(v < 0):" + watch.ElapsedMilliseconds + "ms");
}``````

Mathf.Abs()源码:

``````// Returns the absolute value of /f/.
public static float Abs(float f) { return (float)Math.Abs(f); }

// Returns the absolute value of /value/.
public static int Abs(int value) { return Math.Abs(value); }``````

https://blog.csdn.net/qq_1507...

##### 冰封百度

Unity游戏程序员一枚。生命不息，学习不止。

193 声望
36 粉丝
0 条评论