What overhead is associated with an extension method at runtime? (.NET) [duplicate]

柔情痞子 提交于 2020-01-13 08:40:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!