Mark Needham from Thought Works has recently blogged about using Dictionary instead of If Else statements. The usage of If Else is very common in similar situations however as number of scenarios grow things can become night mare. And at some point of time you have to think about some smart approach such as the one mentioned by Mark.
At first, I thought making entire logic dictionary based may impact performance because of key lookup calls. And that motivated me to write a sample script to verify my understanding. Along with the two approaches, I was also interested to know performance implications using Switch statement. For such quick performance tests, I really love playing with Stopwatch class.
I run the test 1k times and am very happy with the results I got. Along with better readability and maintainability, you get little bit of performance improvement as well. It’s win-win from all the sides. Such tests may seem trivial but it implant solid craftsmanship towards clean code.
Results (in ms):
Using If Else > 1130
Using Switch > 1057
Using Dictionary > 1062