ExpandoObject vs. Dictionary from a performance point of view?

CodingInsomnia picture CodingInsomnia · Aug 19, 2010 · Viewed 9.1k times · Source

A rather simple question really. I'm working on a project where I need to store and retrieve property values dynamically from a kind of context storage. The values will be written now and then and read multiple times. Speed of retrieval is the top priority here, and every nanosecond counts.

Usually, I'd simply implement this with a Dictionary, but with C# 4 and the ExpandoObject I'm thinking that maybe there is a better way? Does anyone have any experience with it? I've seen in other posts that it is NOT implemented using a Dictionary, which makes me curious as to whether it is quicker or slower?

Let me try to clarify with some pseudo code:

// In the main loop
var context = new Context();
context["MyKey"] = 123;
context["MyOtherKey"] = "CODE";
context["MyList"] = new List<int>() { 1, 12, 14 };

foreach(var handler in handlers) {
    handler.DoStuff(context);
}

-

// "Handlers"
class MyFirstHandler {
     void DoStuff(Context context) {
          if (context["MyKey"] > 100)
               context["NewKey"] = "CODE2";
     }
}

class MySecondHandler {
     void DoStuff(Context context) {
          if (context["MyOtherKey"] == "CODE")
             context["MyList"].Add(25); // Remember, it's only Pseudo-code..
     }
}

Well, hopefully you get what I'm trying to do..

I'm also completely open to other suggestions here. I have been toying with the idea of making the Context class statically typed (i.e. actually having a MyKey property, a MyOtherKey property etc), and while it might be possible it would hinder productivity quite a lot for us.

Answer

Jon Skeet picture Jon Skeet · Aug 19, 2010

Speed of retrieval is the top priority here, and every nanosecond counts.

Anything to do with dynamic probably isn't what you're looking for then...

Don't get me wrong, it's pretty heavily optimised - but if you basically just want a string-to-string dictionary lookup, stick with a dictionary.

Alternatively, if you have a limited number of keys, have you considered just having an array with either an enum or a bunch of int constants as the keys?