C# dynamic variable access slow as mollasses in the winter

I recently ran into an issue where I was using the dynamic keyword to simplify my access to Office apis. I had an object that could be a Word document or an Excel workbook. I needed to set the Saved property.

Well, it was easy to use a dynamic and just set it.

i.e.

dynamic doc = GetDocument();

doc.Saved=true;

A lot easier than type checking, casting and a couple if thens.

It turns out, not so much. The use of that small function cost me 8 seconds the first go round. It was much faster the second and third time, but 8 seconds?

I rewrote the code in incredulity as I figured, it must be the Saved property and not the dynamic. Wrong. After rewrite, it took 30ms at the most, 1-2ms hot.

So, wtf? I will research it later, but man. If you write an application that matters, be careful getting all dynamic.

 

Happy coding!