直接从其对象访问类中的方法

时间:2013-04-10 07:34:44

标签: c#

如果一个类只有一个未调用的方法可能很少但很少,那么就不用以下传统方式调用该方法

RarelyCalledClass orarelyCalled = new RarelyCalledClass();
orarelyCalled.rarelyCalledMethod();

我可以这样称呼。

(new RarelyCalledClass()).rarelyCalledMethod();

这会提高性能,因为编译器必须减少操作。

3 个答案:

答案 0 :(得分:3)

性能和代码完全相同。只是你不能再在你的代码中访问实例了。而且可读性也更差(在我和大多数人看来)。

还要记住总是的事情: 过早的微观优化是邪恶的。

描述您的申请。这是一个真正的瓶颈吗?没有?然后不要打扰。

答案 1 :(得分:1)

  

这会增加性能,因为编译器必须做得更少   操作

否。我不这么认为。

我相信你可以用任何反编译器检查他们的IL代码,你也会看到相同的东西。

首先是IL代码;

  .locals init ([0] class _1.RarelyCalledClass orarelyCalled)
  IL_0000:  nop
  IL_0001:  newobj     instance void _1.RarelyCalledClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  callvirt   instance void _1.RarelyCalledClass::rarelyCalledMethod()
  IL_000d:  nop
  IL_000e:  ret

秒一个IL代码;

  .maxstack  8
  IL_0000:  nop
  IL_0001:  newobj     instance void _1.RarelyCalledClass::.ctor()
  IL_0006:  call       instance void _1.RarelyCalledClass::rarelyCalledMethod()
  IL_000b:  nop
  IL_000c:  ret

基于这种结构;

static void Main(string[] args)
{
    //
}
}

class RarelyCalledClass
{
    public RarelyCalledClass()
    {

    }

public void rarelyCalledMethod()
{
    Console.WriteLine("Test");
}
}

只有差异看起来像您的第一个代码使用stloc nad ldloc进行堆栈问题,第二个代码没有。

答案 2 :(得分:0)

编译后它应该是相同的,除非您稍后在某处使用该实例。但是 ILSpy 显示出不同之处:

第一个版本(带作业)

.method private hidebysig static 
    void Main (
        string[] args
    ) cil managed 
{
    // Method begins at RVA 0x2058
    // Code size 13 (0xd)
    .maxstack 1
    .entrypoint
    .locals init (
        [0] class ConsoleApplication1.TestClass obj
    )

    IL_0000: newobj instance void ConsoleApplication1.TestClass::.ctor()
    IL_0005: stloc.0
    IL_0006: ldloc.0
    IL_0007: callvirt instance void ConsoleApplication1.TestClass::TestMethod()
    IL_000c: ret
} // end of method Program::Main

第二个版本(未分配)

.method private hidebysig static 
    void Main (
        string[] args
    ) cil managed 
{
    // Method begins at RVA 0x2058
    // Code size 11 (0xb)
    .maxstack 8
    .entrypoint

    IL_0000: newobj instance void ConsoleApplication1.TestClass::.ctor()
    IL_0005: call instance void ConsoleApplication1.TestClass::TestMethod()
    IL_000a: ret
} // end of method Program::Main

两者均以发布模式构建。