C# unsafe 快速複製陣列

JohnYang819發表於2024-10-11
     /// <summary>
     /// 複製記憶體
     /// </summary>
     /// <param name="dest">目標指標位置</param>
     /// <param name="src">源指標位置</param>
     /// <param name="count">位元組長度</param>
     /// <returns></returns>
     [DllImport("msvcrt.dll")]
     public static extern IntPtr memcpy(IntPtr dest, IntPtr src, int count);
     unsafe static int[] MyCopy(int[] oriInts)
     {
         int[] result = new int[oriInts.Length];
         int lenth= oriInts.Length;
         fixed (int* pOri= oriInts) //fixed語句獲取指向任意值型別、任意值型別陣列或字串的指標
         {
             fixed (int* pResult = result)
             {
                 memcpy(new IntPtr(pResult), new IntPtr(pOri), sizeof(int) * lenth);//注意,第一個引數和第二個引數的順序
             }
         }
         return result;
     }
     static int[] MyCopyB(int[] oriInts)
     {
         int[] result = new int[oriInts.Length];
         for(int i=0;i<oriInts.Length;i++)
         {
             result[i]= oriInts[i];
         }
         return result;
     }

 static void Main(string[] args)
 {
     var a = sizeof(int);
     int[] ori = new int[100000000];
     for(int i = 0; i < ori.Length; i++)
     {
         ori[i] = i;
     }
     Stopwatch sw = new Stopwatch();
     sw.Start();
     int[] copyA= MyCopy(ori);
     sw.Stop();
     Console.WriteLine(sw.ElapsedMilliseconds);
     sw.Restart();
     int[] copyB = MyCopyB(ori);
     sw.Stop();
     Console.WriteLine(sw.ElapsedMilliseconds);
}

相關文章