C# 數組 深拷貝 和 數組傳參


前言

C#中引用類型無法使用const,因此傳參的時候使用引用類型,一定要注意是否會改變其值。下面介紹幾種 數組的 深拷貝方法。

前提

下面的測試代碼有一些前提,

  • sw為Stopwatch
  • nForTimes在這里為10000000

1.Array.Copy(sourceArray, destArray, length)

int[] nArray = new int[4] { 11, 22, 33, 44 };

int[] copyArray = new int[4];

sw.Start();
for (int i = 0; i < nForTimes; i++)
{
	Array.Copy(nArray, copyArray, 4);
}

sw.Stop();

decimal dCopy = sw.ElapsedTicks / (decimal)Stopwatch.Frequency;

Console.WriteLine(dCopy);
  • copy方法運行時間:0.3301541

2.Array.Clone()

int[] cloneArray = new int[4];

sw.Restart();

for (int i = 0; i < nForTimes; i++)
{
	cloneArray = (int[])nArray.Clone();
}

sw.Stop();

decimal dClone = sw.ElapsedTicks / (decimal)Stopwatch.Frequency;

Console.WriteLine(dClone);
  • clone方法運行時間:0.8257813

    因為有明顯的強制類型轉換,所以耗時較長

3.Array.CopyTo

int[] copytoArray = new int[4];

sw.Restart();

for (int i = 0; i < nForTimes; i++)
{
	nArray.CopyTo(copytoArray, 0);
}

sw.Stop();

decimal dCopyTo = sw.ElapsedTicks / (decimal)Stopwatch.Frequency;

Console.WriteLine(dCopyTo);
  • copyto運行時間:0.3313199

4.直接賦值

int[] nDefineArray = new int[4];

sw.Restart();

for (int i = 0; i < nForTimes; i++)
{
    for (int j = 0; j < 4; j++)
    {
    	nDefineArray[j] = nArray[j];
    }
}

sw.Stop();

decimal dDefine = sw.ElapsedTicks / (decimal)Stopwatch.Frequency;

Console.WriteLine(dDefine);
  • 直接賦值運行時間:0.0785752

總結

直接賦值的方式性能明顯強於其他的語法糖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM