匿名函数访问外部变量有gc

直接上测试代码:

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

猜你喜欢

转载自www.cnblogs.com/sifenkesi/p/9762183.html