測試一下 Linq 的 First 速度, 以下是 1000000 次的結果.
using UnityEngine; using System.Linq; using System.Collections.Generic; using System.Diagnostics; public class testListFirst : MonoBehaviour { public int limit = 1000; [System.Serializable] public struct MyStruct { public string str; public int num; } List<MyStruct> m_list = new List<MyStruct>(); void Awake() { m_list.Add(new MyStruct() { str = "str" + Random.Range(0, 100000), num = 1 }); } // Use this for initialization void OnEnable () { int mem = 0; Stopwatch clock = new Stopwatch(); // Case C mem = 0; clock.Reset(); clock.Start(); for (int i = 0; i < limit; i++) { mem += m_list.FirstOrDefault().num; } clock.Stop(); UnityEngine.Debug.Log("list.FirstOrDefault Time used : " + clock.ElapsedMilliseconds + "ms Avg. " + (clock.ElapsedMilliseconds / limit)); // Case A mem = 0; clock.Reset(); clock.Start(); for(int i=0; i< limit; i++) { mem += m_list[0].num; } clock.Stop(); UnityEngine.Debug.Log("list[0] Time used : " + clock.ElapsedMilliseconds + "ms Avg. " + (clock.ElapsedMilliseconds / limit)); clock.Reset(); mem = 0; // Case B mem = 0; clock.Reset(); clock.Start(); for (int i = 0; i < limit; i++) { mem += m_list.First().num; } clock.Stop(); UnityEngine.Debug.Log("list.First Time used : " + clock.ElapsedMilliseconds + "ms Avg. " + (clock.ElapsedMilliseconds / limit)); // Case D mem = 0; clock.Reset(); clock.Start(); for (int i = 0; i < limit; i++) { if(m_list.Count > 0) mem += m_list.First().num; } clock.Stop(); UnityEngine.Debug.Log("Count first + list.First Time used : " + clock.ElapsedMilliseconds + "ms Avg. " + (clock.ElapsedMilliseconds / limit)); // Case E mem = 0; clock.Reset(); clock.Start(); for (int i = 0; i < limit; i++) { if (m_list.Count() > 0) mem += m_list.First().num; } clock.Stop(); UnityEngine.Debug.Log("Count() first + list.First Time used : " + clock.ElapsedMilliseconds + "ms Avg. " + (clock.ElapsedMilliseconds / limit)); } }