回到目錄
字典對象Dictionary<K,V>我們經常會用到,而在大數據環境下,字典使用不當可能引起性能問題,嚴重的可能引起內在的溢出!
下面代碼是對500萬的字典進行測試,首先賦值,然後取出一個隨機機,性能在毫秒級
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(); }
測試結果
而如果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++; } }
在取隨機機時,我們有時使用NewId()這試,但這種開銷依然很大,不建議大家使用,這種只適合在特定的場合用,如EF對IQueryable結果集動態隨機數時,代碼如下
/// <summary> /// sql函數的擴展類 /// </summary> public static class SqlFunctionExtensions { #region 功能方法 /// <summary> /// 在linq to entity中使用SqlServer.NEWID函數 /// </summary> public static Guid NewId() { return Guid.NewGuid(); } #endregion #region 擴展方法 /// <summary> /// 隨機排序擴展方法 /// </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 }
對技術的研究我們在繼續,有時,模稜兩可是不行的!
有時,應該較較真!
回到目錄