static void Main(string[] args) { int[] src = new[] { 1, 2, 3, 4, 5, 6 }; const int destLen = 4;//目標數組大小 int int_size = sizeof(int);//用於獲取值類型的字節大小。 int[] dest = new int[destLen]; //只支持基元類型,按字節偏移復制 Buffer.BlockCopy(src, (src.Length - destLen) * int_size, dest, 0, destLen * int_size); foreach (var i in dest) { Console.Write(i + " "); } Console.WriteLine("\n-------------------------------------------"); string[] srcstr = new[] { "A", "B", "C", "D", "E", "F" }; object[] destobj = new object[src.Length - 2]; //移除的元素個數 const int dellen = 2; //保證不破壞目標數組的元素(回滾)。不裝箱、拆箱、或向下轉換,否則報錯。 //如果srcstr改為src則報錯,因為裝箱。 Array.ConstrainedCopy(srcstr, dellen, destobj, 0, srcstr.Length - dellen); foreach (var s in destobj) { Console.Write(s + " "); } }
對指定數組和目標數組,兩者類型一致的前提下,進行復制10億次,
消耗時間如下:
copy:59.374s,constrainecopy:48.415 s,blockcopy:23.219s
代碼沒什么就是測試下,核心測試如下:
int[] ints = { 1534, 233, 332, 423, 524, 3246, 4357, 734, 567, 43, 34254, 325, 3325, 2423, 345, 575, 235, 1, 342, 1, 6, 54645, 5432, 5 };
int[] dest = new int[ints.Length];
Array.Copy(ints, dest, ints.Length);
Array.ConstrainedCopy(ints, 0, dest, 0, ints.Length);
Buffer.BlockCopy(ints, 0, dest, 0, ints.Length * 4);
注解分析:
1,Array.Copy在CLR處理機制中最靈活,最強大,可裝箱,拆箱復制,可加寬CLR基元類型,可內部判斷實現了IFarmattable接口的兼容轉換,當然這種強大方式必然會帶來一定的性能損失。
2,Array.ConstrainedCopy 對復制要求嚴格,只能是同類型或者源數組類型是目標類型的派生元素類型,不執行裝箱,拆箱,向下轉換
3,Buffer.BlockCopy 則從本質上以字節為復制單位,這在底層語言C,C++的處理優勢上,同理,效率之高可以理解。
當然如果對性能要求不高,Copy足矣,畢竟在上千次復制下,三者基本沒消耗多少時間。使用時可根據項目需求斟酌選擇!
問題:c#如何把某個長數組的一部分復制到另一個短數組里面
byte[] shortAry=new byte[4];
byte[] longAry=new byte[20];
如何把longAry[5,9(不含)]這4個字節復制到shortAry里面?
不要用循環。
用Array.Copy方法將數組或者數組的一部分復制到另個數組。Array.Copy是靜態方法,有多個重載版本。其中常用的是:
public static void Copy( Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);
各個參數含義如下
-
sourceArray —— 源數組
-
sourceIndex —— 表示 sourceArray 中復制開始處的索引
-
destinationArray —— 目標數組,它接收數據
-
destinationIndex —— 表示 destinationArray 中存儲開始處的索引
-
length —— 要復制的元素數目。
用法舉例如下:
(1)復制數組的一部分到另一個數組
int[] src = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int[] dest = new int[4]; // 將數組 src 中元素 2,3,4,5 復制到 dest Array.Copy(src, 1, dest, 0, 4);
(2)復制整個數組
int[] src = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int[] dest = new int[src.Length]; // 將數組 src 所有元素復制到 dest Array.Copy(src, 0, dest, 0, src.Length);