Effective C# Dictionary Usage: Avoid If Statements? 😬

So, accidents happen, and I have come across this article - Effective Dictionary Usage(C#): Avoid If Statements.

Usually, I just ignore such things, but when a well-respected (or I thought so) resource such as medium.com publishes similar things, it's just a bit too much.

There are many use cases for the dictionaries, but not the way it's described in the article.

The main idea of the article is to replace if statements with dynamic dictionaries, which is in my opinion ridiculous.

Runtime dictionaries shall not be used for statically defined behavior.

Implementation proposed by the author is not only harder to implement and debug, but also slower than language native features such as if and switch, which can be optimized by the compiler.

The benchmark provided in the article claims that runtime dictionary is double as fast as statically declared if, but the benchmark itself is not accurate, because the if implementation spams an instance of the Report class on each request, while the dictionary uses just one instance.

To prove my words, I have made a way simpler code snipped to compare if, switch and Dictionary performance in C#.

As you can see, switch provides the best performance, while Dictionary is actually the slowest of the three. When testing on your own, remember to use the Release configuration not Debug.

Written by on
Views: 2528 Comments: 2
Muhammed on 30 September 2019 00:00 says


Khalid on 01 October 2019 08:25 says

👏, sounds reasonable.

It's sad to say, but..
Due to the enormous amount of spam I have decided to disable comments on my website. Feel free to contact me through any other available channel.