这是更快/更高效:字典<字符串对象>或字典<枚举,对象> ;?

问题描述:

枚举类型更快/比字符串作为字典键使用时类型的更有效率?

Are enum types faster/more efficient than string types when used as dictionary keys?

IDictionary<string,object> or IDictionary<enum,object>



作为事实上,它的数据类型是最适合作为字典键为什么?

As a matter of fact, which data type is most suitable as a dictionary key and why?

考虑以下几点:注:仅5个属性为简单

struct MyKeys
{
   public string Incomplete = "IN"; 
   public string Submitted = "SU"; 
   public string Processing="PR"; 
   public string Completed = "CO"; 
   public string Closed = "CL";   
}

enum MyKeys
{
   Incomplete, 
   Submitted, 
   Processing, 
   Completed, 
   Closed
}

哪个如果用作字典中的键上方会更好!

Which of the above will be better if used as keys in a dictionary!

当然,枚举版本更好(当它们都适用,是有意义的,当然) 。不只是性能的(也可以是好还是坏,看Rashack的非常好评论)的,因为它是检查的编译时间和更干净的代码的结果。

Certainly the enum version is better (when both are applicable and make sense, of course). Not just for performance (it can be better or worse, see Rashack's very good comment) as it's checked compile time and results in cleaner code.

和铸造枚举键您可以使用词典&LT规避比较器问题C> INT 指定自定义比较s或

You can circumvent the comparer issue by using Dictionary<int, object> and casting enum keys to ints or specifying a custom comparer.