Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Dictionary vs Class Properties

Coming from a javascript background, collections like dictionaries are often implemented as objects because their properties can be referenced by association:

// js example
var myDict = {
  key1 : "value1",
  key2 : "value2"
};

myDict.key1;    // "value1"
myDict["key1"]; // "value1"

However, in C# it seems we have to choose between static singleton classes and generic dictionaries for each effect. While I like that classes are strongly typed and give intellisense support, Dictionary methods offer flexibility I'm hesitant to give up. Are there performance considerations so great in C# that I should choose one over the other?

like image 697
Daniel Szabo Avatar asked Jan 13 '12 01:01

Daniel Szabo


People also ask

Should I use dictionary or class?

Classes are for bundling related data (and usually code). Dictionaries are for storing key-value relationships, where usually the keys are all of the same type, and all the values are also of one type.

Can a dictionary be a property C#?

Item[] Property. This property is used to get or set the value associated with the specified key in the Dictionary. Here, key is the Key of the value to get or set.

Is dictionary better 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.

Why dictionary is fast in C#?

The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.


2 Answers

Classes are significantly faster than Dictionaries. However, Dictionaries are still very fast. Here is a .NET Fiddle comparing their performance: https://dotnetfiddle.net/NbFw4s

The results:

Dictionary read:  24,544,154 ops/sec
Object read:     383,327,796 ops/sec
-------------------------------------------
Dictionary write: 22,017,208 ops/sec
Object write:    228,458,287 ops/sec

As you can see, classes are an order of magnitude faster than Dictionaries. However, at 24 million operations per second, Dictionaries are still completely acceptable for all but the most performance-sensitive applications (and even then, I would be skeptical that Dictionaries would be the source of performance issues).

The code from the dotnetfiddle:

using System;
using System.Diagnostics;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Stopwatch stopwatch;
        var operations = 15000000;
        var dict = new Dictionary<string, string>() {{"Name", "Bob"}};
        var obj = new Person { Name = "Bob" };

        stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < operations; i++)
        {
            var firstName = dict["Name"];
        }
        stopwatch.Stop();
        Console.WriteLine("Dictionary read: " + (operations / stopwatch.Elapsed.TotalSeconds).ToString("N0") + " ops/sec");
        
        stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < operations; i++)
        {
            var firstName = obj.Name;
        }
        stopwatch.Stop();
        Console.WriteLine("Object read:    " + (operations / stopwatch.Elapsed.TotalSeconds).ToString("N0") + " ops/sec");
        
        Console.WriteLine("-------------------------------------------");
        
        stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < operations; i++)
        {
            dict["Name"] = "Jim";
        }
        stopwatch.Stop();
        Console.WriteLine("Dictionary write: " + (operations / stopwatch.Elapsed.TotalSeconds).ToString("N0") + " ops/sec");
        
        stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < operations; i++)
        {
            obj.Name = "Jim";
        }
        stopwatch.Stop();
        Console.WriteLine("Object write:    " + (operations / stopwatch.Elapsed.TotalSeconds).ToString("N0") + " ops/sec");
        
    }
    
    class Person {
        public string Name;
    }
}
like image 171
TwitchBronBron Avatar answered Nov 09 '22 23:11

TwitchBronBron


If you want to do the kind of duck typing that you do in javascript, but in C#, you could use the ExpandoObject. This is a .Net 4 class. You can dynamically set its properties like:

dynamic myObject = new ExpandoObject();
myObject.namevalue1 = "value1";
myObject.namevalue2 = "value2";

The nice trick that comes in handy with the ExpandoObject in reference to what you are trying to do is that you can access the properties on the ExpandoObject in the same manner as you would access a dictionary value:

var myDictionary = myObject as IDictionary<string, object>;
Console.WriteLine(myDictionary["namevalue1"]); // value1
Console.WriteLine(myDictionary["namevalue2"]); // value2

Keep in mind you are coming from a dynamic language(javascript) to a static language(C#) and the standards and paradigms are very different. Creating a class that represents the data model would be much faster and in general, better form than dynamic objects spewn about.

like image 37
doogle Avatar answered Nov 10 '22 00:11

doogle