什么开销与在运行时的扩展方法有关? (。净) [英] What overhead is associated with an extension method at runtime? (.NET)

查看:95
本文介绍了什么开销与在运行时的扩展方法有关? (。净)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  扩展方法效果

在一个数据处理的应用程序即结合的CPU和/或存储器的访问,是一个行扩展方法noticable的开销?它比普通的函数调用任何更高,或者是它只是一个编译器/ IDE抽象?例如,将下面的函数是不明智的,如果它被称为几向上千倍第二:

 公共静态无效WriteElementString(这XmlTextWriter的作家,字符串名称,int数据)
{
    writer.WriteElementString(姓名,data.ToString());
}
 

解决方案

有没有开销。这只是调用不同的语法的静态方法。产生的IL只是一个普通的电话。

在换言之,开销为您的扩展方法是完全相同

  writer.WriteElementString(名称,数据);
 

,如果你只是叫

  XmlWriterExtensions.WriteElementString(作家,名,数据);
 

...因为生成的IL将完全相同。

在性能方面,向上几千次,第二次是的没有的。开销具有堆一层额外的保护将是完全无关紧要在这一水平......即使该方法不内联,我认为这是非常有可能在这种情况下。

然而,业绩的正常规则:它的所有猜测,直到你已经测量。或者至少,在实际的在这种情况下,冲击最大的是猜测;在扩展方法只是普通的方法,在编译器语法糖是不是猜测。

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());
}

解决方案

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.

这篇关于什么开销与在运行时的扩展方法有关? (。净)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆