问题
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());
}
回答1:
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.
回答2:
No overhead at all, its just a syntactic sugar, its simpley compiler abstraction.
来源:https://stackoverflow.com/questions/1442866/what-overhead-is-associated-with-an-extension-method-at-runtime-net