enum の値をケースバイケースで処理する場合、switch ステートメントと辞書のどちらを使用するのがよいでしょうか?
辞書の方が早いと思います。スペースに関しては、メモリ内でいくらか占有しますが、case ステートメントも、プログラム自体に必要なメモリ内でいくらかのメモリを占有します。要するに、辞書を使用する方が常に良いと思います。
比較のために、2 つの実装を並べて示します。
これらの列挙型を考えると:
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.
}
辞書の速度が向上するだけでなく、コード内の不要な文字列が少なくなります。これは常に辞書を使用する方が良いですか?3番目のより良い方法はありますか?
前もって感謝します。