运行时与扩展方法相关的开销有哪些? (。网)
可能的重复:
扩展方法性能
在受 CPU 和/或内存访问限制的数据处理应用程序中,是一行扩展方法值得注意吗?它是否比普通函数调用更高,或者它只是一个编译器/IDE 抽象?例如,如果每秒调用以下函数数千次,那么它是否是不明智的:
public static void WriteElementString(this XmlTextWriter writer, string name, int data)
{
writer.WriteElementString(name, data.ToString());
}
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());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有任何开销。它只是用不同语法调用的静态方法。生成的IL只是一个普通的调用。
...的开销完全相同
换句话说,您的扩展方法的开销与您刚刚调用
,因为生成的 IL 将完全相同。
就性能而言,“每秒数千次以上”根本不算什么。在该级别上拥有额外级别的堆栈的开销将完全微不足道......即使该方法不是内联的,我相信在这种情况下很可能是内联的。
然而,正常的性能规则是适用的:在测量之前,这都是猜测。或者至少,在这种情况下,实际命中是猜测; “扩展方法只是编译器中带有语法糖的普通方法”并不是猜测。
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
as if you just called
... 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.