.NET Framework - Any way to get the dictionary <> a little faster?

I do a search Dictionary<>in O (n ^ 2) loop and need it to be ridiculously fast. Not this. Does anyone know how to implement Dictionary<>? I test the performance of a dictionary with an isolated test case after running my code through the profiler, and determining the search in the Dictionary is the main part of the processor time. My test code is as follows:

Int32[] keys = new Int32[10] { 38784, 19294, 109574, 2450985, 5, 398, 98405, 12093, 909802, 38294394 };

Dictionary<Int32, MyData> map = new Dictionary<Int32, MyData>();
//Add a bunch of things to map


timer.Start();
Object item;
for (int i = 0; i < 1000000; i++)
{
   for (int j = 0; j < keys.Length; j++)
   {
      bool isFound = map.ContainsKey(keys[j]);
      if (isFound)
      {
         item = map[keys[j]];
      }
   }
}
timer.Stop();

ContainsKey and map [] are two slow parts (equally slow). If I add TryGetValue, it is almost identical in speed to ContainsKey. Here are some interesting facts.

A Dictionary<Guid, T> , Dictionary<Int32, T>. Dictionary<String, T> , Guid. A Dictionary<Byte, T> 50% , Ints. , O (log n), , . - , Hashtable, .NET Hashtable, , .

, , , . . , , 10 , 2 000 . - - , ? !

Mike

+3
5

-, , Reflector a while .

" 10 , 2000 , ".

. , .

, . , , , .. 2000 10 .

+7

, , . OutOfMemoryExceptions, . int, OutOfMemoryException. null , .

, , .

public class QuickLookup<T> where T : class
{
    private T[] _postives = new T[short.MaxValue + 1];
    private T[] _negatives = new T[short.MaxValue + 1];
    public T this[short key]
    {
        get
        {
            return key < 0 ? _negatives[(key * -1) - 1] : _postives[key];
        }
        set
        {
            if (key < 0)
                _negatives[key * -1] = value;
            else
                _postives[key] = value;
        }
    }
}
+1

10 2000 , 20000 , , ? :

List<MyData> = new List(); 

//add all items to list indexed by their key (RAM is not an issue right?)

item = ItemList[key];

.

0

, , 10 . , - . / , , ( , ).

, ; , , , , .

, , - - (.. ), .

0

The insight of the internal workings of the hash table is the point. You should definitely use TryGetValue as your entire inner loop:

  map.TryGetValue(keys[j], out item);

Running ContainsKey and Item [] does the hard part (search) twice. Extra, if extra keys [j] are insignificant, but will add up in a narrow cycle. Using foreach over your keys is likely to be slower, but profiling may be required depending on the actual contents of the loop.

0
source

Source: https://habr.com/ru/post/1758666/


All Articles