First, test results:
The efficiency is almost the same. There is no need to change the writing method, which one you prefer.
Test code:
using UnityEngine; using UnityEditor; using System.Diagnostics; /// <summary> ///Execution time test /// ZhangYu 2019-04-13 /// </summary> public class TimeTest : MonoBehaviour { private static Stopwatch watch; private void Start() { Execute(); } [MenuItem("CONTEXT/TimeTest/implement")] private static void Execute() { watch = new Stopwatch(); // Data length 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(); foreachTest(array); watch.Stop(); string msgFor1 = string.Format("For1: {0}s", watch.Elapsed); // For2 watch.Reset(); watch.Start(); foreachTest(array); watch.Stop(); string msgFor2 = string.Format("For2: {0}s", watch.Elapsed); print(msgForeach); print(msgFor1); print(msgFor2); } // (1)0.7035506s // (2)0.7174406s // (3)0.7001000s // (4)0.7012998s // (5)0.7009337s public static void foreachTest(int[] array) { foreach (int item in array) { } } // (1)0.7014426s // (2)0.7172180s // (3)0.6987379s // (4)0.6987784s // (5)0.7051741s public static void forTest1(int[] array) { for (int i = 0; i < array.Length; i++) { } } // (1)0.7006860s // (2)0.7160505s // (3)0.6997564s // (4)0.7024032s // (5)0.7004985s public static void forTest2(int[] array) { int length = array.Length; for (int i = 0; i < length; i++) { } } }
Test results:
Excluding the error of the running environment, the efficiency of for loop and foreach loop is basically the same in dozens of test results. For2 method optimizes the length value, but there is no obvious performance gap, so which one do for and foreach prefer? There is no need to change the writing method or habit to improve the efficiency.