淺談C#各類數組直接的數據復制/轉換。本站提示廣大學習愛好者:(淺談C#各類數組直接的數據復制/轉換)文章只能為提供參考,不一定能成為您想要的結果。以下是淺談C#各類數組直接的數據復制/轉換正文
之前做Opengl法式,用的的C#的SharpGL這個庫,外面有各類奇異綁定的函數,好比原型為:
void glInterleavedArrays(uint format, int stride, void * pointer);
的函數被他綁定成:
private static extern void glInterleavedArrays(uint format, int stride, 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, 0, ptr, from.Length); Marshal.Copy(ptr, dTo, 0, 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, 0, 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, 0, 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, 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, 0, dTo, 0, 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#各類數組直接的數據復制/轉換就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。