「毎日Unity」の技術ブログ

開発で役立つ情報を発信する

【UnityC#】Math.Abs、Mathf.Absの速度比較

Math.Abs、Mathf.Absの速度比較をしたので結果を残しておきます。

[ 環境 ]

Unity 2018.4.14.f1

[ 比較結果 ]

Math.Abs 6 ms
Mathf.Abs 18 ms

[ スクリプト ]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class PerformanceComparison : MonoBehaviour
{
    void Start()
    {
        System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();

        int Count = 1000000;

        //Math.Abs

        StopWatch.Restart();

        for(float i = 0; i < Count; i++)
        {
            float Temporary = Math.Abs(i);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //Mathf.Abs

        StopWatch.Restart();

        for(float i = 0; i < Count; i++)
        {
            float Temporary = Mathf.Abs(i);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);
    }
}