測試 Linq First 的速度

測試 Linq First 的速度

測試一下 Linq 的 First 速度, 以下是 1000000 次的結果.

LinqTest

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));
	}
	
	
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料