匿名函數訪問外部變量有gc
阿新 • • 發佈:2018-10-09
bug https truct new 分享圖片 ber action avi sin
直接上測試代碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestStructGC : MonoBehaviour { public struct StructDef { public System.Action act; public StructDef(System.Action callback) { act = callback; } }public int memberValue; private void Update() { // 使用匿名函數,不訪問外部函數,0 gc { UnityEngine.Profiling.Profiler.BeginSample("*** Test1 ***"); StructDef obj = new StructDef(null); UnityEngine.Profiling.Profiler.EndSample(); }// 使用匿名函數,訪問臨時變量,112B gc { int tmp = 1; UnityEngine.Profiling.Profiler.BeginSample("*** Test2 ***"); StructDef obj = new StructDef(() => { var v = tmp; }); UnityEngine.Profiling.Profiler.EndSample(); } // 使用匿名函數,訪問外部變量,112B gc{ UnityEngine.Profiling.Profiler.BeginSample("*** Test3 ***"); StructDef obj = new StructDef(() => { Debug.LogError(memberValue); }); UnityEngine.Profiling.Profiler.EndSample(); } // 不使用匿名函數,0 gc { UnityEngine.Profiling.Profiler.BeginSample("*** Test4 ***"); StructDef obj = new StructDef(actCallback); UnityEngine.Profiling.Profiler.EndSample(); } } #region optimize for test4 private System.Action actCallback; public TestStructGC() { actCallback = LocalCallback; } private void LocalCallback() { Debug.LogError(memberValue); } #endregion }
參考:https://blog.uwa4d.com/archives/Anonymous_heapmemory.html
匿名函數訪問外部變量有gc