「毎日Unity」の技術ブログ

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

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

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

[ 環境 ]

Unity 2018.4.14.f1

[ 比較結果 ]

Math.Clamp 8 ms
Mathf.Clamp 9 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.Clamp

        StopWatch.Restart();

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

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //Mathf.Clamp

        StopWatch.Restart();

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

        Debug.Log(StopWatch.ElapsedMilliseconds);
    }
}