Dot-Net-3.5
擴展方法性能
/*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 上。
我想將 TypeX 轉換為 Int 或 Boolean,這個操作是我在程式碼中很多地方都在做的一件常見的事情。我想知道這是否會導致性能下降。我嘗試使用 Reflector 解釋 IL 程式碼,但並不擅長。對於上面的範例,可能不會有任何性能下降。一般來說,我想知道在使用擴展方法時對性能的影響。
擴展方法只是一個編譯時更改:
x.GetValueAsBoolean()到
Extensions.GetValueAsBoolean(x)這就是所涉及的全部內容 - 將看起來像實例方法呼叫的內容轉換為對靜態方法的呼叫。
如果靜態方法沒有性能問題,那麼將其作為擴展方法不會引入任何新問題。
編輯:IL,根據要求…
取這個樣本:
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"); } }
Extension這是and的 ILNormal:.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如您所見,它們完全相同。