Permanently changing dynamic datatype in C #

First post here, please be careful.

Let's say we had this hypothetical use case where we needed a dynamic data type that was constantly switching between multiple types.

// Declare stuff
const string dataString = "String";
const double dataDouble = 2.0;
dynamic dynamicThing = dataString;
var w = new Stopwatch();

// Measure performance of switching types once
w.Start();
dynamicThing = dataDouble;
double dynamicDouble = dynamicThing;
dynamicThing = dataString;
string dynamicString = dynamicThing;
w.Stop();

      

In my development box, this example shows the clock at about 4936519 ticks. I managed to get an implementation that does what I need in 25529 ticks. However, I believe it might be too slow.

Am I missing any other .NET Framework way that could be faster than using dynamic?

Remember that this is a requirement to constantly handle the switch, because if there was a switch only after the DLR would just cache the dynamic value, and that would be very fast.

Thanks for reading.

+3


source to share


1 answer


It seems that when using value types, the fastest way is to use object and cast.

object objectThing = dataString;
w.Restart();
objectThing = dataDouble;
double objectDouble = (double)objectThing;
objectThing = dataString;
string objectString = (string)objectThing;
w.Stop();

      



Only 14 ticks.

+2


source







All Articles