關於爲什麼保存Transform等引用效率會更高

轉自:http://blog.sina.com.cn/s/blog_5b6cb9500101fkal.html
正常來說,大部分同學一般get transform都直接gameobject.transform使用。但往往,你會發現有些人會將transform引用保存起來,例如:

private Transform myTransform;
void Awake() {
    myTransform = transform;
}

然後使用myTransform替代this.transform。如果你不知道u3d內部實現獲取方式你肯定會以爲這人腦抽水了,有直接的不用,還自己保存起來。

this.transform並不是變量,而是一個get/set屬性(property)。

using System;
using System.Runtime.CompilerServices;
using UnityEngineInternal;
namespace UnityEngine
{
    public class Component : Object
    {
        public extern Transform transform
        {
            [WrapperlessIcall]
            [MethodImpl(MethodImplOptions.InternalCall)]
            get;
        }
    }
}

調用this.transform實際上是一個調用intenal method的過程(這是用C/C++寫的,不是MONO的)。值得注意的是這個調用方法略慢,因爲你需要調用外部的CIL(aka interop),花費了額外的性能。

估計大概的效率(沒測試,以後有時間再弄,大家可以參考下文章最後的鏈接):

GetComponent是this.transform的10倍消耗時間。
this.transform是保存了引用myTransform的1.5倍的消耗時間。(因爲新版優化了不少)

實際上:

如果你是偶爾調用一下transform的話,那就不要保留它的引用了,直接this.transform。

如果是Update中,每一幀都要改變的話,還是保留一下this.transform的引用吧。畢竟倘若一大堆東西的話,能快不少呢。


詳細參考:

http://forum.unity3d.com/threads/130359-How-does-caching-an-objects-transform-make-the-game-run-faster

http://forum.unity3d.com/threads/96908-Unity-should-internally-cache-transform-for-a-valid-speed-boost

http://forum.unity3d.com/threads/130365-CachedMB
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章