简体   繁体   中英

In C#, is a dictionary whose keys are of type Type slower than a dictionary whose keys are of type ulong?

I currently have the following:

ConcurrentDictionary<ulong, MyEventHandler> eventHandlers;

and an indefinite number of classes:

class MyClass1
{
    public const ulong MyKey = 0;
    ... 
}

class MyClass2
{
    public const ulong MyKey = 1;
    ... 
}

...etc...

My dictionary is to hold an event handler that corresponds to the type of class. Right now I'm using the MyKey member as the key to my dictionary, which works fine.

However, when other classes are developed now and in the future, I don't want to make the developer worry about having to have a key.

How much slower (if at all) is doing the following:

ConcurrentDictionary<Type, MyEventHandler> eventHandlers;

and then using the typeof operator to get the Type to index into my dictionary?

That way I never have to worry about a key.

I do care a lot about speed, because even though the dictionary likely wont have more than 100 entries, typeof will be called and the dictionary will be accessed thousands of times per second.

Types are represented and identified by metadata tokens, which I guess are 32-bit integers. The typeof operator makes a lookup in metadata tables to find the Type represented by the metadata token.

I believe that the JIT compiler will optimize metadata table accesses very well and therefore I don't think that you should notice any performance difference in reality. I would actually not be surprised if using Type as key would even prove to be slightly faster.

Since using Type as key would make the code much easier to maintain I would recommend that approach unless you can prove that the other approach is clearly more performant.

If your dictionary is a singleton/multiton you can create a generic type to speed up indexation by this pattern :

static class MyHandler<T>
{
    static public MyEventHandler Value;
}

instead of

CurrentDictionary[typeof(Class1)]

you can do

MyHandler<Class1>.Value

This depends on how GetHashCode() is implemented. WHen the .Net framework code "finds" an object in a dictionary, it calls this method to perform the search. Obviously, in any Dictionary that uses a key based on a type where the implementation of GetHashCode() takes substantially longer than simply retrieving the value of a long , or a uLong , that dictionary will exhibit proportionally poorer performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM