transformは遅い説の検証

qiita.com

こちらの記事によるとtransformは内部でGetComponentをしているので遅いらしいです。

気になったので自分でも試してみました。

テスト環境

まずは以下の様なコードで。

using UnityEngine;
using System.Collections;

public class TransformProfile : MonoBehaviour {
    protected Transform cachedTransform;
    System.Diagnostics.Stopwatch stopWatch0 = new System.Diagnostics.Stopwatch();
    System.Diagnostics.Stopwatch stopWatch1 = new System.Diagnostics.Stopwatch();
    const int cLoopMax = 1000;

	void Start () {
        cachedTransform = transform;

        stopWatch0.Reset();
        stopWatch0.Start();
        for( int i = 0; i < cLoopMax; ++i )
        {
            transform.localPosition += Vector3.one;
        }
        stopWatch0.Stop();
        Debug.Log( "transoform: " + stopWatch0.Elapsed.TotalMilliseconds.ToString() + "msec" );

        stopWatch1.Reset();
        stopWatch1.Start();
        for( int i = 0; i < cLoopMax; ++i )
        {
            cachedTransform.localPosition += Vector3.one;
        }
        stopWatch1.Stop();
        Debug.Log( "cached transoform: " + stopWatch1.Elapsed.TotalMilliseconds.ToString() + "msec" );
	}
}

PC(Editor)

cachedTransform 0.144 msec
transform 0.384 msec

iPhone

cachedTransform 0.174 msec
transform 0.295 msec


ざっくり2倍〜3倍ほどキャッシングしてあげたほうが早そうです。ただ、上記のコードだとメモリキャッシュが効いてまうので、あまり差が出にくいです。

そこで以下の様なコードでも試します。1フレーム経つ間にキャッシュが汚れることが期待し、コルーチン使って毎フレーム少しづつtransformに触る感じにしております。

using UnityEngine;
using System.Collections;

public class TransformProfile : MonoBehaviour {
    protected Transform cachedTransform;
    System.Diagnostics.Stopwatch stopWatch0 = new System.Diagnostics.Stopwatch();
    System.Diagnostics.Stopwatch stopWatch1 = new System.Diagnostics.Stopwatch();
    const int cLoopMax = 1000;

	void Start () {
        cachedTransform = transform;

        StartCoroutine(processTransform());
        StartCoroutine(processCachedTransform());
    }

	IEnumerator processTransform() {
        stopWatch0.Reset();
        for( int i = 0; i < cLoopMax; ++i )
        {
            stopWatch0.Start();
            transform.localPosition += Vector3.one;
            stopWatch0.Stop();
            yield return null;
        }
        Debug.Log( "transoform: " + stopWatch0.Elapsed.TotalMilliseconds.ToString() + "msec" );
    }

	IEnumerator processCachedTransform() {
        stopWatch1.Reset();
        for( int i = 0; i < cLoopMax; ++i )
        {
            stopWatch1.Start();
            cachedTransform.localPosition += Vector3.one;
            stopWatch1.Stop();
            yield return null;
        }
        Debug.Log( "cached transoform: " + stopWatch1.Elapsed.TotalMilliseconds.ToString() + "msec" );
    }
}

PC(Editor)

cachedTransform 0.586 msec
transform 4.415 msec

iPhone

cachedTransform 2.561 msec
transform 7.053 msec

先程より差がでました。PCだと8倍ぐらい差がでます?

なんとなくiPhoneでも、もうちょいちゃんとキャッシュを汚せれば優位な差が出る気がします。

transformを使う際は一度キャッシュしてから利用したほうが良さそうですね。

Divide Number Puzzle

Divide Number Puzzle

  • Ken Watanabe
  • Games
  • Free
play.google.com