更好地利用哈希表或交换机的情况下 [英] Better use HashTable or switch case
问题描述
我不知道哪一个更好。我需要解析的输入字符串的每一个字符,并获得用于该字符一个替换字符串。对于某些对象的所有字母数字字符被允许使用这样的switch / case会造成大量的代码,并降低可读性和可维护性,但我可以用一个静态方法。使用哈希表也需要大量的代码
I'm not sure which one is better. I need to parse each character of an input string and get a replacing string for the character. For some objects all alphanumeric characters are allowed so using switch/case will cause a lot of code and reduce readability and maintainability but I can use a static method. Using a HashTable also requires a lot of code
使用静态方法:
private static string EncodeChar(char c)
{
var symbols = string.Empty;
switch (c)
{
case '0':
symbols = "Test";
break;
case '1':
symbols = "Hello";
break;
[...]
}
symbols;
}
使用哈希表:
private static Hashtable table = CreateTable();
private static Hashtable CreateTable()
{
var table = new HashTable();
table.Add('0',"Test");
table.Add('1', "Hello");
[...]
return table;
}
private static string EncodeChar(char c)
{
return table.ContainsKey(c) ? table[c].ToString() : string.Empty;
}
编码方式:
The Encode method:
public void Encode()
{
string output = string.Empty;
for (int i = 1; i < Data.Length; i++)
{
output = string.Concat(output, EncodeChar(Data[i]));
}
EncodedData = output;
}
有什么优势/关于性能和内存分配缺点是什么?
What are the advantages/disadvantages concerning performance and memory allocation?
推荐答案
我会使用的HashTable
,因为代码的可读性和可维护性:你有一天决定从一个XML文件加载托换弦,这样你就不会改变代码来改变映射。
I'd use the HashTable
, because the code is more readable and maintainable: you could one day decide to load the subtitution strings from an XML file, so that you won't change the code to change the mappings.
这篇关于更好地利用哈希表或交换机的情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!