Performance IDictionary <Type, Object> vs generic Type Property

edit . I based this question on the false assumption that the typical type instance queries that I performed would do the same job as when creating generic types created at runtime. Those in my wiring are available to the compiler, so they can compile them into address search queries. I'm still very interested in what .MakeGenericType does behind the scenes.

I just made a quick comparison between getting a value from an IDictionary and getting a value from a generic type with a static property.

100,000,000 search results:

Dictionary: 14.5246952 Generic Type: 00.2513280

What magic does .NET use in the background to map a Generic instance so fast? I would think that for searching you need to use something similar to a hash table. Maybe it's SPEED ... I don't know! You?

Here is my test harness - I'm sure it is full of errors, so let me know what needs to be fixed!

void Main()
{
    var sw = new Stopwatch();
    var d = new Dictionary<Type, object>() 
    { 
     { typeof(string), new object() },
     { typeof(int), new object() } 

    };
    var stringType = typeof(string);
    var intType = typeof(int);
    sw.Start();
    for (var i = 0; i < 100000000; i++)
    {
        Debug.Assert(d[stringType] != d[intType]);
    }
    sw.Stop();
    sw.Elapsed.Dump();
    sw.Reset();

    Lookup<string>.o = new object();
    Lookup<int>.o = new object();
    sw.Start();
    for (var i = 0; i < 100000000; i++)
    {
        Debug.Assert(Lookup<string>.o != Lookup<int>.o);
    }
    sw.Stop();
    sw.Elapsed.Dump();
}

class Lookup<T>
{
    public static object o;
}
+3
source share
2 answers

I think that comparisons to your generics are done at compile time, while the dictionary does a search at runtime.

+2
source

JIT- o. . , , . , , . :

000000f8  mov         eax,dword ptr ds:[02785D0Ch] 
000000fd  cmp         eax,dword ptr ds:[02785D10h] 

.

+4

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


All Articles