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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With