扩展方法性能

编程入门 行业动态 更新时间:2024-10-26 10:40:10
本文介绍了扩展方法性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 /*I have defined Extension Methods for the TypeX like this*/ public static Int32 GetValueAsInt(this TypeX oValue) { return Int32.Parse(oValue.ToString()); } public static Boolean GetValueAsBoolean(this TypeX oValue) { return Boolean.Parse(oValue.ToString()); } TypeX x = new TypeX("1"); TypeX y = new TypeX("true"); //Method #1 Int32 iXValue = x.GetValueAsInt(); Boolean iYValue = y.GetValueAsBoolean(); //Method #2 Int32 iXValueDirect = Int32.Parse(x.ToString()); Boolean iYValueDirect = Boolean.Parse(y.ToString());

没有得到通过而TYPEx说,我应该定义内而TYPEx这些方法,而不是扩展)我就可以了(没有控制忘乎所以实际的类,我定义它是SPListItem。

Dont get carried away by TypeX saying that I should define those methods inside TypeX rather than the Extension) I have no control on it (Actual Class I defined it is on SPListItem.

我想转换,而TYPEx为int或布尔和这个操作是,我做的很多,在code的地方之一常见的事情。我想知道这会造成性能degrade.I试图跨preT IL code。使用反射,但我不擅长。可以是上述的例子有不会是任何性能劣化。总的来说,我想知道有关于性能的影响,同时使用扩展方法。

I wanted to convert the TypeX to Int or Boolean and this operation is one Common thing that I am doing in lots of Places in the code. I wanted to know will this cause performance degrade.I tried to interpret IL code using Reflector, but am not good at it. May be for the above example there wont be any performance degrade. In general I wanted to know about the implications with Regard to the Performance while using the Extension methods.

推荐答案

扩展方法的只是的从一个编译时的变化:

Extension methods are just a compile-time change from:

x.GetValueAsBoolean()

Extensions.GetValueAsBoolean(x)

这是所有的参与 - 翻译看起来像一个实例的方法调用将调用一个静态方法

That's all that's involved - translating what looks like an instance method call into a call to a static method.

如果您还没有与静态方法的性能问题,然后使它的扩展方法不会引入任何新的问题。

If you don't have performance problems with the static method, then making it an extension method won't introduce any new problems.

编辑:IL,根据要求...

IL, as requested...

以这个样本:

using System; public static class Extensions { public static void Dump(this string x) { Console.WriteLine(x); } } class Test { static void Extension() { "test".Dump(); } static void Normal() { Extensions.Dump("test"); } }

下面是IL为扩展和正常:

.method private hidebysig static void Extension() cil managed { // Code size 13 (0xd) .maxstack 8 IL_0000: nop IL_0001: ldstr "test" IL_0006: call void Extensions::Dump(string) IL_000b: nop IL_000c: ret } // end of method Test::Extension .method private hidebysig static void Normal() cil managed { // Code size 13 (0xd) .maxstack 8 IL_0000: nop IL_0001: ldstr "test" IL_0006: call void Extensions::Dump(string) IL_000b: nop IL_000c: ret } // end of method Test::Normal

正如你所看到的,他们是完全一样的。

As you can see, they're exactly the same.

更多推荐

扩展方法性能

本文发布于:2023-11-05 18:59:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:性能   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!