Unity Delegates固定產生112Byte gc的問題

本文固定鏈接,轉載請評論點贊

一、起因:

在推特上看到一個消息,如圖:
在這裏插入圖片描述

於是我試驗了一下。

二、我的試驗:

代碼如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AboutDelegates : MonoBehaviour
{
    // Start is called before the first frame update
    void UpdatePoints(Action<float> f)
    {
        f(1);
    }

    // Update is called once per frame
    void Update()
    {
        UpdatePoints(Sin);
    }

    private void Sin(float t)
    {
        
    }
}


Profile裏深度分析如下:
在這裏插入圖片描述

看結果跟推特上的一樣,112B的GC。

三、一個字曰:變

按照他的代碼,我們改一下,代碼如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AboutDelegates : MonoBehaviour
{
    // Start is called before the first frame update

    private Action<float> mActionF = Sin;


    void UpdatePoints(Action<float> f)
    {
        f(1);
    }

    // Update is called once per frame
    void Update()
    {
        UpdatePoints(mActionF);
    }

    private static void Sin(float t)
    {
        
    }
}

運行結果如圖:
在這裏插入圖片描述

嗯,看來確實是有這個問題。哇咔咔。

暫時從推特上的回覆來說,沒有太好的答案解釋這個問題。反正大家注意一下。如果你研究出來了,請留言。

四、後續:

後來我改了下代碼,因爲怕因爲static方法影響。代碼改成如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AboutDelegates : MonoBehaviour
{
    // Start is called before the first frame update

    private Action<float> mActionF = null;

    private void Start()
    {
        mActionF = Sin;
    }


    void UpdatePoints(Action<float> f)
    {
        f(1);
    }

    // Update is called once per frame
    void Update()
    {
        UpdatePoints(mActionF);
    }

    private void Sin(float t)
    {
        
    }
}

結果其實是沒有變化的。依舊沒有112b的gc。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章