是var x = new Stuff(); x.DoStuff();快new Stuff().DoStuff();吗?
我不知道为什么,但我在我的代码中注意到第一种方法使它更快,任何人都知道哪一种更快,为什么?
实际上第二个应该更快,因为它执行更少的操作.我们以此程序为例:
class Program
{
public void Foo() { }
static void Main()
{}
static void Method1()
{
var x = new Program();
x.Foo();
}
static void Method2()
{
new Program().Foo();
}
}
Run Code Online (Sandbox Code Playgroud)
以下是在Release模式下编译时Method1和Method2的外观:
.method private hidebysig static void Method1() cil managed
{
.maxstack 1
.locals init (
[0] class Program x)
L_0000: newobj instance void Program::.ctor()
L_0005: stloc.0
L_0006: ldloc.0
L_0007: callvirt instance void Program::Foo()
L_000c: ret
}
.method private hidebysig static void Method2() cil managed
{
.maxstack 8
L_0000: newobj instance void Program::.ctor()
L_0005: call instance void Program::Foo()
L_000a: ret
}
Run Code Online (Sandbox Code Playgroud)
当然,永远不应该问这种微优化问题.