先说测试结果:
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