C# unsafe 快速复制数组

JohnYang / 2024-10-12 / 原文

     /// <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);
}