zoukankan      html  css  js  c++  java
  • C# 接口持有结构体会导致装箱问题

    问题起源:void DistpatchEvent(EventType, IEventData)

    这里的 IEventData是一个接口,代表事件参数。

    为了避免每次发送事件产生GC,决定事件参数使用struct,但struct不能继承,所以这里只能使用接口作为基类。

    但将结构体传给接口时会发生装箱操作,产生GC。

    public class testStructGC : MonoBehaviour
    {
    
        // Start is called before the first frame update
        void Start()
        {
            var ot = new PlayerMoveCmd();
            ICmd ic = new PlayerMoveCmd();
        }
    
        // Update is called once per frame
        void Update()
        {
            
        }
    }

    对应的IL代码,可以看到

    ICmd ic = new PlayerMoveCmd(); 
    这一行产生了装箱操作
        .method private hidebysig 
            instance void Start () cil managed 
        {
            // Method begins at RVA 0x20b0
            // Code size 25 (0x19)
            .maxstack 1
            .locals init (
                [0] valuetype PlayerMoveCmd ot,
                [1] class ICmd ic,
                [2] valuetype PlayerMoveCmd
            )
    
            // {
            IL_0000: nop
            // PlayerMoveCmd playerMoveCmd = default(PlayerMoveCmd);
            IL_0001: ldloca.s 0
            IL_0003: initobj PlayerMoveCmd
            // ICmd cmd = default(PlayerMoveCmd);
            IL_0009: ldloca.s 2
            IL_000b: initobj PlayerMoveCmd
            IL_0011: ldloc.2
            IL_0012: box PlayerMoveCmd
            IL_0017: stloc.1
            // }
            IL_0018: ret
        } // end of method testStructGC::Start


  • 相关阅读:
    Search Insert Position
    *Set Matrix Zeroes
    Spiral Matrix II
    *Spiral Matrix
    combination的eclipse运行结果
    [?]*Combination(递归调用好难)
    [?]*Subset
    *3Sum Closest
    Why am I getting an Unreachable Statement error in Java?
    windows下,emacs的配置文件在哪儿?
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/13637188.html
Copyright © 2011-2022 走看看