浅谈C#各种数组直接的数据复制/转换
之前做Opengl程序,用的的C#的SharpGL这个库,里面有各种奇怪绑定的函数,比如原型为: void glInterleavedArrays(uint format,int stride,void * pointer); 的函数被他绑定成: private static extern void glInterleavedArrays(uint format,int[] pointer); 然后我就被逼着学习了各种float[] 转 int[] 的方法,比较他们的效率(其实我还是感觉c++比较快,一个指针类型转换,欧啦) 下面是我写的各种数组赋值转换的方法和结果对比。 1.Marshal.Copy,存在数组到IntPtr,IntPtr到数组的2次拷贝【当T2不是Copy支持的类型会出错,之所以引入dynamic dTo 是因为使用T2[] dTo 无法编译通过】,处理2000000*100字节1120.0018ms public static T2[] Arr2Arr<T1,T2>(T1[] from) where T1: struct where T2 :struct { int byteNum = from.Length * from[0].Sizeof(); T2 testByte = new T2(); dynamic dFrom = from; dynamic dTo = new T2[byteNum / testByte.Sizeof()]; IntPtr ptr = Marshal.AllocHGlobal(byteNum); Marshal.Copy(dFrom,ptr,from.Length); Marshal.Copy(ptr,dTo,dTo.Length); return dTo; } 2.unsafe的方法,通过指针获得IntPtr,减少了一次复制,速度变快【当T2不是Copy支持的类型会出错,之所以引入pFrom是因为无法fixed泛型T1[]】,处理2000000*100字节695.9993ms public unsafe static T2[] Arr2Arr<T1,T2>(T1[] from,void * pFrom) where T1 : struct where T2 : struct { int byteNum = from.Length * from[0].Sizeof(); T2 testByte = new T2(); dynamic dTo = new T2[byteNum / testByte.Sizeof()]; IntPtr ptr = new IntPtr(pFrom); Marshal.Copy(ptr,dTo.Length); return dTo; } 3.通过GCHandle获得IntPtr,然后复制【当T2不是Copy支持的类型会出错】,处理2000000*100字节930.0481ms public static T2[] Arr2Arr2<T1,T2>(T1[] from) where T1 : struct where T2 : struct { var gch = GCHandle.Alloc(from,GCHandleType.Pinned); IntPtr ptr = gch.AddrOfPinnedObject(); int byteNum = from.Length * from[0].Sizeof(); T2 testByte = new T2(); dynamic dTo = new T2[byteNum / testByte.Sizeof()]; Marshal.Copy(ptr,dTo.Length); gch.Free(); return dTo; } 4.Array.Copy的方法,原生的数组复制方法【没有了Copy,可以处理任意值类型】,处理2000000*100字节620.042ms public static T2[] Arr2Arr3<T1,T2>(T1[] from) where T1 : struct where T2 : struct { int byteNum = from.Length * from[0].Sizeof(); T2 testByte = new T2(); T2[] dTo = new T2[byteNum / testByte.Sizeof()]; Array.Copy(from,dTo.Length); return dTo; } 5.通过Buffer.BlockCopy拷贝数组,速度最快,感觉类似于c++的memcpy【没有了Copy,可以处理任意值类型】,处理2000000*100字节300.0329ms public static T2[] Arr2Arr4<T1,T2>(T1[] from) where T1 : struct where T2 : struct { int byteNum = from.Length * from[0].Sizeof(); T2 testByte = new T2(); T2[] dTo = new T2[byteNum / testByte.Sizeof()]; Buffer.BlockCopy(from,byteNum); return dTo; } 测试部分代码: byte[] from = new byte[100]; from[0] = 1; from[1] = 1; var last = DateTime.Now; for (int i = 0; i < 2000000; i++) { 。。。 } Console.WriteLine((DateTime.Now- last).TotalMilliseconds); //sizeof扩展方法internal static class ExFunc { public static int Sizeof(this ValueType t) { return Marshal.SizeOf(t); } } 综上所述,Buffer.BlockCopy 适用场合最广泛,效率最高。 以上这篇浅谈C#各种数组直接的数据复制/转换就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |