代码之家  ›  专栏  ›  技术社区  ›  Kusek

扩展方法性能

  •  8
  • Kusek  · 技术社区  · 16 年前
                /*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中定义那些方法,而不是扩展名),我对它没有控制(实际的类I定义它在splistem上)。

    我想将typex转换为int或boolean,这个操作是我在代码中很多地方所做的一个常见操作。我想知道这会不会导致性能下降。我试图用Reflector解释IL代码,但不擅长。可能在上面的例子中不会有任何性能下降。一般来说,我希望在使用扩展方法时了解与性能相关的影响。

    4 回复  |  直到 16 年前
        1
  •  24
  •   Jon Skeet    16 年前

    扩展方法是 只是 编译时更改自:

    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 Normal :

    .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
    

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

        2
  •  4
  •   Wyatt Barnett    16 年前

    扩展方法只是编译器巫术,因此它们在运行时具有正常方法的所有性能影响。

        3
  •  2
  •   Razzie    16 年前

    因为扩展方法都是在编译时绑定的(您怎么说的?).

        4
  •  1
  •   tvanfosson    16 年前

    在最坏的情况下,您将有一个额外的函数调用。说真的,尽管如此,我还是希望它能够像现在这样简单地内联这段代码,并且没有任何明显的效果。

    推荐文章