C#復(fù)制數(shù)組的兩種方式及效率比較
如何高效地進(jìn)行數(shù)組復(fù)制?
如果把一個(gè)變量值復(fù)制給另外一個(gè)數(shù)組變量,那么2個(gè)變量指向托管堆上同一個(gè)引用。
如果想在托管堆上創(chuàng)建另外的一份數(shù)組實(shí)例,通常使用Array.Copy方法。
class Program { static void Main(string[] args) { int[] a = {1, 3, 6}; int[] b =new int[a.Length]; Array.Copy(a,0,b,0,a.Length); MyArrCopy myArrCopy = new MyArrCopy(); myArrCopy.Display(a); Console.ReadKey(); } } public class MyArrCopy { public void Display(int[] arr) { for (int i = 0; i < arr.Length; i++) { if (i != 0) { Console.Write(","); } Console.Write(arr[i]); } } }
在數(shù)據(jù)量大的情況下,使用Buffer.BlockCopy方法將會擁有更高的復(fù)制效率。
分別測試使用Buffer.BlockCopy和Array.Copy的區(qū)別。
public class CopyTest { private int[] _myArr;//數(shù)組源 private int[] _blockArr=new int[10000];//使用 Buffer.BlockCopy的目標(biāo)數(shù)組 private int[] _copyArr=new int[10000];//使用Array.Copy的目標(biāo)數(shù)組 public CopyTest(int[] myArr) { _myArr = myArr; } public void TestBlockCopy() { Stopwatch sw = new Stopwatch(); sw.Start(); Buffer.BlockCopy(_myArr, 0,_blockArr,0,_myArr.Length); sw.Stop(); Console.WriteLine("使用Buffer.BlockCopy方法:" + sw.ElapsedTicks); } public void TestNormalCopy() { Stopwatch sw = new Stopwatch(); sw.Start(); Array.Copy(_myArr, 0, _copyArr,0, _myArr.Length); sw.Start(); Console.WriteLine("使用Array.Copy方法:" + sw.ElapsedTicks); } }
客戶端。
int[] a = new int[10000]; for (int i = 0; i < 10000; i++) { a[i] = i; } var copyTest = new CopyTest(a); copyTest.TestBlockCopy(); copyTest.TestNormalCopy(); Console.ReadKey();
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
C#數(shù)值轉(zhuǎn)換-顯式數(shù)值轉(zhuǎn)換表(參考)
就是在將一種類型轉(zhuǎn)換成另外一種類型時(shí),需要額外的代碼來完成這種轉(zhuǎn)換。2013-04-04c#之利用API函數(shù)實(shí)現(xiàn)動畫窗體的方法詳解
本篇文章是對c#中利用API函數(shù)實(shí)現(xiàn)動畫窗體的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06精簡高效的C#網(wǎng)站優(yōu)化經(jīng)驗(yàn)技巧總結(jié)
這篇文章主要為大家介紹了精簡高效的C#網(wǎng)站優(yōu)化經(jīng)驗(yàn)技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04