Unity C# for和foreach效率比较

49次阅读

共计 1406 个字符,预计需要花费 4 分钟才能阅读完成。

先说测试结果:效率几乎完全一样,不用特意改变写法,喜欢哪种用哪种。
测试代码:
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();
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++) {

}
}
}

测试结果:排除运行环境的误差,for 循环和 foreach 循环在数十次的测试结果中,效率基本是完全一样的,For2 方法优化了一下 length 的取值,但没什么明显的性能差距,所以 for 和 foreach 喜欢那种用哪种吧,不用为了提高效率特意改变写法或习惯。

正文完
 0