標籤:factor text mil using count 儲存 read eric 資料檢索
測試環境:
Win7 SP1、8G記憶體、3.4GHz 4核
測試代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Reflection;using System.Diagnostics;namespace FactoryMode{ public class TestObject { public string memberString { get; set; } public long memberBigInt { get; set; } } [Serializable] public class Program : MarshalByRefObject { static long TotalCount = 2000000; static long FisrtLv = 500000; static long SecondLv = 1000000; static long ThirdLv = 1500000; static void Main(string[] args) { //鏈表測試資源準備 var ObjectList = new List<TestObject>(); for (int i = 0; i < TotalCount; i++) { var newTestObject = new TestObject(); newTestObject.memberString = i.ToString(); newTestObject.memberBigInt = i; ObjectList.Add(newTestObject); } //尋找1 var stopWatch1 = Stopwatch.StartNew(); var result1 = ObjectList.Find(p => p.memberBigInt == SecondLv); var lastElapsedTime1 = stopWatch1.ElapsedMilliseconds; Console.WriteLine("Condition 1: {0} ms.", lastElapsedTime1); Console.WriteLine("result1: {0}.", result1.memberString); //字典測試資源準備 var ObjectDictionary = new Dictionary<string, TestObject>(); for (int i = 0; i < TotalCount; i++) { var newTestObject = new TestObject(); newTestObject.memberString = i.ToString(); newTestObject.memberBigInt = i; ObjectDictionary.Add(newTestObject.memberString, newTestObject); } //尋找2 var stopWatch2 = Stopwatch.StartNew(); var result2 = ObjectDictionary[Convert.ToString(ThirdLv)]; var lastElapsedTime2 = stopWatch2.ElapsedMilliseconds; Console.WriteLine("Condition 2: {0} ms.", lastElapsedTime2); Console.WriteLine("result2: {0}.", result2.memberString); Console.Read(); } }}
測試結果:
鏈表檢索:每50w 12ms;
Hash檢索:0ms;
測試代碼2:
//寫入1 var stopWatch3 = Stopwatch.StartNew(); for (int i = 0; i < FisrtLv; i++) { ObjectList[i].memberBigInt += 1; } var lastElapsedTime3 = stopWatch3.ElapsedMilliseconds; Console.WriteLine("Condition 3: {0} ms.", lastElapsedTime3); //寫入2 var stopWatch4 = Stopwatch.StartNew(); for (int i = 0; i < FisrtLv; i++) { ObjectDictionary[Convert.ToString(i)].memberBigInt += 1; } var lastElapsedTime4 = stopWatch4.ElapsedMilliseconds; Console.WriteLine("Condition 4: {0} ms.", lastElapsedTime4);
測試結果2:
鏈表寫入:12ms;
Hash寫入:143ms;(根據散列函數得到了新的儲存位置,資料轉移開銷)
技術參考:http://blog.sina.com.cn/s/blog_7880b6e30100xi94.html。
注意點:
雖然Hash具有O(1)的資料檢索效率,但它空間開銷卻通常很大,是以空間換取時間,所以Hashtable適用於讀取操作頻繁,寫入操作很少的操作類型。
引申思考:
在實際的應用中,應避免將所有的常用、不常用的資料都放在同一個資料結構中,無論是使用自訂的記憶體結構或者是redis,都應該定時將到期資料放入二級緩衝,為一級緩衝瘦身。
在遊戲伺服器應用中,一個伺服器應將資料分為記憶體資料、冷備資料,登陸時將冷備資料載入至記憶體(登陸較慢可容忍),單服熱資料容量一般不會超過5w層級,資料結構的效能可接受。
在之前一個http短串連項目的應用中,每次協議都直接從redis讀取資料,處理完畢之後寫入redis,但是 redis 實際上沒有冷資料,這樣隨著已耗用時間的推移,效率會越來越低。
鏈表與Hash檢索實測