匿名函数GC

匿名函数
  • 测试代码如下
public class TestGC : MonoBehaviour
{

	public class Student
	{
		public string name;
	}

    // Update is called once per frame
    void Update()
    {
		//no gc
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg ***");
		Action method = () => { Debug.Log ("hello world"); };
		UnityEngine.Profiling.Profiler.EndSample ();
		//112 B
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg int ***");
		int a = 12;
		Action method2 = () => { Debug.Log ("hello world"); Debug.Log (a); };
		UnityEngine.Profiling.Profiler.EndSample ();
		//136 B
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg obj ***");
		Student stu = new Student () { name = "jiayajie" };
		Action method3 = () => { Debug.Log (stu.name);};
		UnityEngine.Profiling.Profiler.EndSample ();
		//112 B
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg member ***");
		Action method4 = LogName;
		UnityEngine.Profiling.Profiler.EndSample ();

		//112 B
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg member param ***");
		Action method5 = LogId;
		UnityEngine.Profiling.Profiler.EndSample ();

		//112 B
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg member stu ***");
		Action method6 = LogStu;
		UnityEngine.Profiling.Profiler.EndSample ();

		//112 B
		UnityEngine.Profiling.Profiler.BeginSample ("*** AnoymousFunctionWithoutArg method param ***");
		Do (LogName);
		UnityEngine.Profiling.Profiler.EndSample ();
	}

	void  Do(Action bigOne)
	{
		
	}
	void LogName ()
	{
		Debug.Log ("Hello world");
	}


	int id = -1;
	void LogId ()
	{
		Debug.Log ($"Hello world_{id}");
	}

	Student student = new Student () { name = "houzhimin"};
	void LogStu ()
	{
		Debug.Log ($"Hello world_{student.name}");
		Debug.Log ($"Hello world_{id}");
	}

}
结论
  • 匿名函数在不引用外部变量的情况下不会产生GC Action func = ()=>{Debug.Log("A"); }
  • 成员函数赋值给委托变量的时候无论是否引用变量都会GCAction func = method;
  • 当把成员函数赋值给函数参数的时候会产生GCLogName(method)
  • 当委托执行的时候也会产生GCfunc.Invoke()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值