The foundation is the top priority ~ Performance determined by the design of <K, V> in Dictionary
Back to directory
Dictionary objects <K, V> are often used. In Big Data Environments, improper Dictionary usage may cause performance problems, and serious problems may cause internal overflow!
- We recommend that you use Tuple <T>
- When the dictionary key is searched, the time complexity is O (1), so there is no performance problem, so do not wish it
The following code tests the 5 million dictionary. First, assign a value and then retrieve a random machine. The performance is within milliseconds.
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(); }
Test Results
If the value uses the tuple <t> type, the performance will plummet!
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++; } }
We sometimes use NewId () for random machines, but this overhead is still large and is not recommended for use only in specific scenarios, for example, when EF performs a dynamic random number on the IQueryable result set, the Code is as follows:
/// <Summary> /// SQL function extension class /// </summary> public static class SqlFunctionExtensions {# region Function Method /// <summary> // use SqlServer. NEWID function // </summary> public static Guid NewId () {return Guid. newGuid ();} # endregion # region Extension Method // <summary> // random sort Extension Method /// </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}
We are continuing to study technology. Sometimes, ambiguity cannot be achieved!
Sometimes, it should be more true!
Back to directory