Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpandoObject vs. Dictionary from a performance point of view?

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.

like image 626
CodingInsomnia Avatar asked Aug 19 '10 14:08

CodingInsomnia


People also ask

When to use ExpandoObject c#?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.

How do I know if I have ExpandoObject property?

For ExpandoObject, you can simply check whether the property is defined as a key in the underlying dictionary. For other implementations, it might be challenging and sometimes the only way is to work with exceptions.


1 Answers

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?

like image 171
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet