基礎(chǔ)才是重中之重~Dictionary<K,V>里V的設(shè)計決定的性能
字典對象Dictionary<K,V>我們經(jīng)常會用到,而在大數(shù)據(jù)環(huán)境下,字典使用不當(dāng)可能引起性能問題,嚴(yán)重的可能引起內(nèi)在的溢出!
- 字典的值建議為簡單類型,反正使用Tuple<T>
- 字典的鍵在查找時,時間復(fù)雜度為O(1),性能不會有任何問題,所以不要愿望它
下面代碼是對500萬的字典進(jìn)行測試,首先賦值,然后取出一個隨機(jī)機(jī),性能在毫秒級
static void Draw() { int count = 5000000; Console.WriteLine("test:{0} feeds", count); List<GoldCoinInfo> list = new List<GoldCoinInfo>(); list.Add(new GoldCoinInfo { Id = 100, GoldValue = 5, LeftCount = count, TotalCount = count }); var dic = new Dictionary<int, int>(); int _index = 0; Stopwatch sw = new Stopwatch(); sw.Restart(); foreach (var gold in list) { for (int j = 0; j < gold.LeftCount; j++) { dic.Add(_index, gold.Id); _index++; } } sw.Stop(); Console.WriteLine("step1:{0} ms", sw.ElapsedMilliseconds); sw.Restart(); var prizeIndex2 = GenerateRandom(dic.Keys.Max(), 1).FirstOrDefault(); Console.WriteLine("step3:{0} ms,value:{1}", sw.ElapsedMilliseconds, dic[prizeIndex2]); sw.Stop(); }
測試結(jié)果
而如果value使用了tuple<t>類型,那性能就一落千丈了!
var dic = new Dictionary<int, Tuple<int, int>>(); int _index = 0; Stopwatch sw = new Stopwatch(); sw.Restart(); foreach (var gold in list) { for (int j = 0; j < gold.LeftCount; j++) { dic.Add(_index, new Tuple<int, int>(gold.Id, gold.GoldValue)); _index++; } }
在取隨機(jī)機(jī)時,我們有時使用NewId()這試,但這種開銷依然很大,不建議大家使用,這種只適合在特定的場合用,如EF對IQueryable結(jié)果集動態(tài)隨機(jī)數(shù)時,代碼如下
/// <summary> /// sql函數(shù)的擴(kuò)展類 /// </summary> public static class SqlFunctionExtensions { #region 功能方法 /// <summary> /// 在linq to entity中使用SqlServer.NEWID函數(shù) /// </summary> public static Guid NewId() { return Guid.NewGuid(); } #endregion #region 擴(kuò)展方法 /// <summary> /// 隨機(jī)排序擴(kuò)展方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public static IQueryable<T> OrderByNewId<T>(this IEnumerable<T> source) { return source.AsQueryable().OrderBy(d => NewId()); } #endregion }
對技術(shù)的研究我們在繼續(xù),有時,模棱兩可是不行的!
有時,應(yīng)該較較真!
浙公網(wǎng)安備 33010602011771號