首页 > 其他 > 详细

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

时间:2018-10-09 19:48:36      阅读:232      评论:0      收藏:0      [点我收藏+]

 

直接上测试代码:

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

原文:https://www.cnblogs.com/sifenkesi/p/9762183.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!