Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: switch vs dictionary for string keys

I've got a situation where I have a business object with about 15 properties of different types. The business object also has to implement an interface which has the following method:

object GetFieldValue(string FieldName);

I can see 2 ways of implementing this method:

Use a switch statement:

switch ( FieldName )
{
    case "Field1": return this.Field1;
    case "Field2": return this.Field2;
    // etc.
}

Use a dictionary (SortedDictionary or HashTable?):

return this.AllFields[FieldName];

Which would be more efficient?

Added: Forgot to say. This method is for displaying the item in a grid. The grid will have a column for each of these properties. There will routinely be grids with a bit over 1000 items in them. That's why I'm concerned about performance.

Added 2:

Here's an idea: a hybrid approach. Make a static dictionary with keys being property names and values being indices in array. The dictionary is filled only once, at the startup of the application. Every object instance has an array. So, the lookup would be like:

return this.ValueArray[StaticDictionary[FieldName]];

The dictionary filling algorithm can use reflection. The properties itself will then be implemented accordingly:

public bool Field1
{
    get
    {
        object o = this.ValueArray[StaticDictionary["Field1"]]; 
        return o == null ? false : (bool)o;
    }
    set
    {
        this.ValueArray[StaticDictionary["Field1"]] = value;
    }
}

Can anyone see any problems with this?

It can also be taken one step further and the ValueArray/StaticDictionary can be placed in a separate generic type ValueCollection<T>, where T would specify the type for reflection. ValueCollection will also handle the case when no value has been set yet. Properties could then be written simply as:

public bool Field1
{
    get
    {
        return (bool)this.Values["Field1"];
    }
    set
    {
        this.Values["Field1"] = value;
    }
}

And in the end, I'm starting to wonder again, if a simple switch statement might not be both faster and easier to maintain....

like image 350
Vilx- Avatar asked Aug 26 '09 11:08

Vilx-


People also ask

Is a dictionary faster than a switch statement?

By iterating over both methods and comparing, I am getting that the dictionary is slightly faster, even when "a", "b", "c", "d" is expanded to include more keys. Why is this so? The compiler may actually turn your switch into a dictionary at some point, so make sure you test this with the real input.

Why is dictionary faster than list C#?

The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.

What is the alternative of dictionary in C#?

A HashSet, similar to a Dictionary, is a hash-based collection, so look ups are very fast with O(1). But unlike a dictionary, it doesn't store key/value pairs; it only stores values. So, every objects should be unique and this is determined by the value returned from the GetHashCode method.

Could a dictionary be used instead of a switch statement?

Using if else is a old programming method, we can replace a long if else with switch statements. If we have so many if else satements or switch statements it is not good coding. We can use a dictionary for solving this problem.


2 Answers

switch:      good efficiency, least maintainable
dictionary:  good efficiency, better maintainability
reflection:  least efficient, best maintainability

Hint: ignore efficiency and worry about maintainability only, unless you've actually tested performance and found it be be an issue.

I'm not saying reflection is your only choice, just that it would allow you to add/remove and rename properties as needed, and not need to keep the switch statement or dictionary in sync.

like image 100
Ash Avatar answered Dec 10 '22 15:12

Ash


Because you are using strings Dictionary will probably be faster. Switch will essentially get translated to a hashtable when using strings. But if you are using ints or similar it gets translated to a jump table and will be faster.

see this answer and question for more details

Best bet is to profile it and find for sure

like image 25
Mike Two Avatar answered Dec 10 '22 14:12

Mike Two