【C#】关于Array.Copy 和 GC

关于Array.Copy 和 GC

csharp 复制代码
	//一个简单的 数组copy   什么情况下会触发GC呢
    [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
    public static void Copy(Array sourceArray,
                            long sourceIndex,
                            Array destinationArray,
                            long destinationIndex,
                            long length);

当源和目标的类型不一致,由小转大,比如由byte 到 short ,int 都会触发GC ,我不知道内部机制如何,可能是拆装箱导致的 ,不确定,不过在实际开发中确实出现了这种问题,所以使用的时候 类型要匹配

贴一段测试代码

csharp 复制代码
   void Update()
    {
        var start = DateTime.Now;
        for (int i = 0; i < this.inputData.Length; i++)
        {
            this.inputData[i] = -125;
            var a = Mathf.Abs(this.inputData[i]);
            a = Mathf.Clamp(a, 0, 1023);
            this.inputData[i] = (short)(a * 255 / 1023);
        }
        Debug.Log($"<color=#ff00ff>CPU cost : {(DateTime.Now - start).TotalMilliseconds}</color>");

        start = DateTime.Now;
        **byte[] outData = new byte[size];**
        this.ComputeData(ref outData); //GPU

        int[] outData2 = new int[this.size];
        Array.Copy(outData, 0, outData2, 0, outData.Length);
        
        Debug.Log($"<color=#ffff00>GPU cost : {(DateTime.Now - start).TotalMilliseconds}</color>");
    }

    private void ComputeData(ref int[] outPutBytes)
    {
        //if (this.inputbuffer == null)
        {
            inputbuffer = new ComputeBuffer(this.inputData.Length, 4); //定义缓冲区(参数:数组长度、每个数组元素占用字节数)
        }

        //if (this.outputbuffer == null)
        {
            outputbuffer = new ComputeBuffer(this.outputData.Length, 4);
        }

        inputbuffer.SetData(this.inputData); //待计算数据加载入缓冲区
        this.shader.SetBuffer(this.k, "inputData", inputbuffer); //定义输入口
        this.shader.SetBuffer(this.k, "outputData", outputbuffer); //定义输出口

        this.shader.Dispatch(this.k, this.inputData.Length / 1024, 1, 1); //开始执行(参数:主函数下标、线程组的XYZ个数)
        outputbuffer.GetData(this.outputData); //缓冲区获得计算好的数据

        for (int i = 0; i < this.outputData.Length; i++)
        {
            outPutBytes[i] = (byte)this.outputData[i];
        }

        inputbuffer.Dispose(); //清除缓存
        outputbuffer.Dispose();
    }

运行情况

GC

恐怖如斯啊~~~

相关推荐
咩咩啃树皮7 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
灯澜忆梦7 小时前
GO_并发编程---定时器
开发语言·后端·golang
鱟鲥鳚7 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
-银雾鸢尾-7 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-8 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白9 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司9 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地10 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun31415910 小时前
TCP超时重传机制是为了解决什么问题?
java
段一凡-华北理工大学11 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化