Possible Duplicate:
Extension Method Performance
In a data crunching application that is CPU and/or memory access bound, is the overhead of a one line extension method noticable? Is it any higher than a normal function call, or is it simply a compiler/IDE abstraction? For instance, would the following function be ill advised if it was being called upwards of several thousand times a second:
public static void WriteElementString(this XmlTextWriter writer, string name, int data)
{
writer.WriteElementString(name, data.ToString());
}
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.
Extension methods enable developers to add custom functionality to data types that are already defined without creating a new derived type. Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type.
Extension Methods are a new feature in C# 3.0. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in . NET.
There's no overhead. It's just a static method called with different syntax. The IL generated is just a normal call.
In other words, the overhead for your extension method is exactly the same for
writer.WriteElementString(name, data);
as if you just called
XmlWriterExtensions.WriteElementString(writer, name, data);
... because the generated IL will be exactly the same.
In terms of performance, "upwards of several thousand times a second" is nothing. The overhead for having an extra level of stack will be utterly insignificant at that level... even if the method isn't inlined, which I believe it's very likely to be in this case.
However, the normal rule of performance applies: it's all guesswork until you've measured. Or at least, the actual hit in this case is guesswork; the "extension methods are just normal methods with syntactic sugar in the compiler" isn't guesswork.
No overhead at all, its just a syntactic sugar, its simpley compiler abstraction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With