运行时与扩展方法相关的开销有哪些? (。网)

发布于 2024-08-05 06:49:23 字数 442 浏览 6 评论 0原文

可能的重复:
扩展方法性能

在受 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘味果▽酱 2024-08-12 06:49:23

没有任何开销。它只是用不同语法调用的静态方法。生成的IL只是一个普通的调用。

...的开销完全相同

writer.WriteElementString(name, data);

换句话说,您的扩展方法的开销与您刚刚调用

XmlWriterExtensions.WriteElementString(writer, name, data);

,因为生成的 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

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.

听不够的曲调 2024-08-12 06:49:23

完全没有开销,它只是一个语法糖,它简单的编译器抽象。

No overhead at all, its just a syntactic sugar, its simpley compiler abstraction.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文