Fasterflect vs. C# 4.0 Dynamic
As .NET 4.0 final release will hit the market pretty soon, it’s worth discussing the value of Fasterflect in the face of C# 4.0’s dynamic keyword. (If you aren’t familiar with C# 4.0 dynamic, you should read my article on C# 4.0 before continuing.)
To recall, Fasterflect was designed to address 2 key disadvantages of .NET Reflection: ease of use and performance. As seen in my article about C# 4.0, the dynamic keyword nicely addresses the easy of use with a resulting syntax looking even nicer than Fasterflect. How about performance?
I improved the benchmark application of Fasterflect to add some benchmark code comparing between the performance of C# 4.0 dynamic and Fasterflect. Here is result of method invocation benchmark.

While performing slower than Fasterflect’s cached API, C# dynamic performs much better than Fasterflect’s standard API. (Not surprisingly, the C# dynamic binding doesn’t resort to the slow reflection mechanism internally.)
With this awareness in mind, together with the understanding about the features of C# dynamic and Fasterflect, let’s discuss about areas where Fasterflect shines even in the face of C# 4.0 dynamic:
- C# dynamic doesn’t handle invocations performed based on dynamic information (i.e. field name read from XML file).
- C# dynamic does handle certain types of dynamic invocations, including static method invocation, static property invocation and constructor invocation.
- C# dynamic doesn’t handle non-public members. So you’ll receive exception if trying to, say, invoke a private method.
- When performance is more critical than readability then the Fasterflect’s cached API might be favored over C# dynamic.
Granted, there should be workarounds for the first 3 items. For example, if you want to invoke static method dynamically with C# dynamic, you would have to workaround like the approach described in this article. However, the approach uses reflection behind the scene so you would have the same performance issue to start with.
This doesn’t say that Fasterflect is better than C# dynamic though. While both share a couple of features and maybe used interchangeably in some scenarios, they also have different problems of their own to address. There are many things that you can do with C# dynamic that you couldn’t do with Fasterflect, e.g. implementing an interceptor to dynamically handle all method invocations (or missing methods) etc. So, pick the right tool for your problem at hand.

Recent Comments