Optimizing Dynamic Performance

Nov 8, 2008 at 3:04 PM
It seems to me that all this constant compilation of dynamic expressions could start to take its toll on performance if we use the fix:Lambda converter a lot (as I tend to do).

The thing is, while the lambda is dynamic from the perspective that it must be specified as text and interpreted at runtime, it's not generally dynamic in the sense that it will change during runtime (not that that isn't possible, just that it's usually the case otherwise), and especially not between instances of the same class. I noticed you are in fact compiling each dynamic expression to a delegate, which should make executing that delegate fast, once compiled, but that the compilation is occurring every time a new instance is created.

I did a simple test by writing a line to the console every time ConstructOperation is called, and with what code it is called with, and I see a lot of duplication.

In other words, if I have two instances of the same object which uses a lambda converter, then the converter (though identical) is compiled twice. I think all this extra compiling is really slowing things down, so I'm going to do an experiment to see if I can speed things up by sharing compiled delegates across instances.

My first attempt will simply store references to each delegate constructed in a Dictionary keyed by the actual textual expression itself, which will persist for the life of the application, just to see if this offers any noticable performance boost, and if so we can explore better implementations from there (for one thing using weak references to allow delegates to be collected when no longer in use).
Nov 26, 2008 at 1:59 AM
It turned out my (less than reliably-performed) preliminary tests showed no significant change in performance and actually (may have) shown a slight decrease in performance, which is odd because I can't logically explain that. It seems to me that a single dictionary look-up should be much faster than recompiling an expression, no matter how simple it is, but alas it doesn't appear to be as much of an issue as I originally thought. Still, my tests were very poorly done so there could be very different results elsewhere.