SYSK 370: The Performance Cost of Extension Methods

First, for those who may not be familiar with this feature, .NET 3.5 allows developers to add methods to existing types without using inheritance or partial classes by creating static methods that can be invoked by using instance method syntax.

When I first heard about this feature, it reminded me of the decorator pattern in OOP (I’m not speaking of the implementation, but the concept… )

Since there are lots of examples for C# developers, and very few for VB.NET, here is an example of adding Serialize and Deserialize methods to any object written in VB.NET:

Now, to the promised performance impact…I ran and timed a test that created 100,000,000 instances of an object with the extension methods above, and compared the execution time to doing the same but without the extension methods.Just to be clear, I didn’t actually execute the extension methods…My goal was to find out if simply adding the extension methods would significantly impact the object instantiation time by running the following code:

I’m not sure why this would be surprising. The extended class is completely decoupled from the extension method. e.g. the compilation of the extended class could have have occured before the existence of the extension method. Therefore instantiation code must not be affected by an extension method because it can be compiled before the extension method is created.