【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

恐怖如斯啊~~~

相关推荐
Kuo-Teng1 分钟前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展
初见无风1 分钟前
3.4 Boost库intrusive_ptr智能指针的使用
开发语言·boost
王元_SmallA4 分钟前
服务器公网IP、私网IP、弹性IP是什么?区别与应
java·后端
程序猿20235 分钟前
Python每日一练---第六天:罗马数字转整数
开发语言·python·算法
葵续浅笑23 分钟前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
装不满的克莱因瓶33 分钟前
【Java架构师】各个微服务之间有哪些调用方式?
java·开发语言·微服务·架构·dubbo·restful·springcloud
杨筱毅40 分钟前
【穿越Effective C++】条款13:以对象管理资源——RAII原则的基石
开发语言·c++·effective c++
N 年 后1 小时前
cursor和传统idea的区别是什么?
java·人工智能·intellij-idea
CodeLongBear1 小时前
从Java后端到Python大模型:我的学习转型与规划
java·python·学习
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 94: 最长的斐波那契子序列的长度
java·数据结构·算法·leetcode·深度优先·动态规划