【发布时间】:2013-07-12 00:09:10
【问题描述】:
在逐个处理枚举值时,使用 switch 语句还是字典更好?
我认为字典会更快。在空间方面,它占用了一些内存,但是case语句也会占用一些内存,只是在程序本身所需的内存中。所以底线我认为只使用字典总是更好。
下面是两个实现并排比较:
鉴于这些枚举:
enum FruitType
{
Other,
Apple,
Banana,
Mango,
Orange
}
enum SpanishFruitType
{
Otra,
Manzana, // Apple
Naranja, // Orange
Platano, // Banana
Pitaya // Dragon fruit, only grown in Mexico and South American countries, lets say
// let's say they don't have mangos, because I don't remember the word for it.
}
下面是使用 switch 语句的方法:
private static SpanishFruitType GetSpanishEquivalent(FruitType typeOfFruit)
{
switch(typeOfFruit)
{
case FruitType.Apple:
return SpanishFruitType.Manzana;
case FruitType.Banana:
return SpanishFruitType.Platano;
case FruitType.Orange:
return SpanishFruitType.Naranja;
case FruitType.Mango:
case FruitType.Other:
return SpanishFruitType.Otra;
default:
throw new Exception("what kind of fruit is " + typeOfFruit + "?!");
}
}
下面是使用字典的方法:
private static Dictionary<FruitType, SpanishFruitType> EnglishToSpanishFruit = new Dictionary<FruitType, SpanishFruitType>()
{
{FruitType.Apple, SpanishFruitType.Manzana}
,{FruitType.Banana, SpanishFruitType.Platano}
,{FruitType.Mango, SpanishFruitType.Otra}
,{FruitType.Orange, SpanishFruitType.Naranja}
,{FruitType.Other, SpanishFruitType.Otra}
};
private static SpanishFruitType GetSpanishEquivalentWithDictionary(FruitType typeOfFruit)
{
return EnglishToSpanishFruit[typeOfFruit]; // throws exception if it's not in the dictionary, which is fine.
}
字典不仅可以提高速度,而且代码中不必要的字符串也更少。那么使用字典总是更好吗?还有第三种更好的方法吗?
提前致谢。
【问题讨论】:
-
您每秒执行多少次这些查找?如果它小于一个 bajillion,请不要担心。只需选择最容易阅读/维护的方法即可。
-
实际切换速度更快
-
当 Switch 语句包含超过 7 个选项时,编译器将把它翻译成一个“字典”(更准确地说是一个哈希),所以如果它对您来说更具可读性,请使用 switch 语句并让编译器尽最大努力进行优化。
标签: c# dictionary enums switch-statement