Better use HashTable or switch case

痞子三分冷 提交于 2020-01-11 04:14:09

问题


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

Using the static method:

 private static string EncodeChar(char c)
    {
        var symbols = string.Empty;

        switch (c)
        {
            case '0':
                symbols = "Test";
                break;
            case '1':
                symbols = "Hello";
                break;
            [...]
        }

        symbols;
    }

Using HashTable:

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?


回答1:


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.




回答2:


Hashing is faster as you can directly access the 'encoded string'

for example, If you assume that all characters are '9', so it will have to evaluate 8 if conditions before executing the right statement, each time you process a character.

That's just a worst-case example while using the switch()




回答3:


The switch code does the same thing as the alternative, but it's much more readable which should be the main concern here.

I would however use an abstract factory to get one of a number of different encoding implementations for different types of input.



来源:https://stackoverflow.com/questions/9277415/better-use-hashtable-or-switch-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!