先說測試結果:
for比foreach快,for循環不額外定義length彷佛更快測試
測試代碼:優化
using UnityEngine; using UnityEditor; using System.Diagnostics; /// <summary> /// 執行時間測試 /// ZhangYu 2019-04-13 /// </summary> public class TimeTest : MonoBehaviour { private static Stopwatch watch; private void Start() { Execute(); } [MenuItem("CONTEXT/TimeTest/執行")] private static void Execute() { watch = new Stopwatch(); // 數據長度 int total = 100000000; int[] array = new int[total]; for (int i = 0; i < total; i++) { array[i] = i + 1; } // Foreach watch.Reset(); watch.Start(); ForeachTest(array); watch.Stop(); string msgForeach = string.Format("Foreach: {0}s", watch.Elapsed); // For1 watch.Reset(); watch.Start(); ForTest1(array); watch.Stop(); string msgFor1 = string.Format("For1: {0}s", watch.Elapsed); // For2 watch.Reset(); watch.Start(); ForTest2(array); watch.Stop(); string msgFor2 = string.Format("For2: {0}s", watch.Elapsed); print(msgForeach); print(msgFor1); print(msgFor2); } // (1)0.7167410s // (2)0.7127794s // (3)0.7215614s // (4)0.7183622s // (5)0.7190012s public static void ForeachTest(int[] array) { foreach (int item in array) { } } // (1)0.5252327s // (2)0.5546530s // (3)0.5545011s // (4)0.5576123s // (5)0.5543154s public static void ForTest1(int[] array) { for (int i = 0; i < array.Length; i++) { } } // (1)0.5314386s // (2)0.5835369s // (3)0.5908804s // (4)0.5880162s // (5)0.5835442s public static void ForTest2(int[] array) { int length = array.Length; for (int i = 0; i < length; i++) { } } }
測試結果:
排除運行環境的偏差,for循環和foreach循環在數十次的測試結果中,for更快一點,For2方法優化了一下length的取值,彷佛定義了length比直接使用array.Length更慢了一點兒,仍是直接使用array.length吧。spa