for foreach 效率比較


很多時候,我們在選擇循環的時候,會考慮用那個循環好一點,這個好一點就是指效果高一點!今天我對於for, foreach循環做了個性能測試,測試代碼如下:

// Performance test of for loop.      

private void ForLoopPerformance()      

{         

System.Diagnostics.Debug.WriteLine("ForLoopPerformance: ");

string[] array = new string[10000000];

DateTime d1 = DateTime.Now;         

for (int i = 0; i < array.Length; i++)         

{            

  Console.Write(array[i]);         

}         

System.Diagnostics.Debug.WriteLine(DateTime.Now.Ticks - d1.Ticks);

        

DateTime d2 = DateTime.Now;         

int len = array.Length;         

for (int i = 0; i < len; i++)         

{            

  Console.Write(array[i]);         

}         

System.Diagnostics.Debug.WriteLine(DateTime.Now.Ticks - d2.Ticks);

        

DateTime d3 = DateTime.Now;         

foreach (string str in array)         

{

            Console.Write(str);         

}         

System.Diagnostics.Debug.WriteLine(DateTime.Now.Ticks - d3.Ticks);      

}

 

運行結果如下(每次運行結果會有差異):

ForLoopPerformance:
2904263  // for
2804116  // for
2703969  // foreach

 

結論:

foreach性能最好,其次就是第二個for循環,因為相對於第一個來說,第二個for循環只要進行一個array.GetLength來獲取數組的最大下標!

 

當然了,這個結論也不是絕對的,在選擇for, foreach的時候,應該考慮以下幾點:

1. 如果只是讀數據,優先選擇foreach,因為效率高,而且代碼簡單,方便;

2. 如果要寫數據,就只能選擇for了,而且選擇第二個for效率更高!


免責聲明!

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



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