在 C# 中创建新模型和设置属性的最快方法是什么?

Kri*_*ian 0 c# properties instantiation

我想知道这两种实例化类/模型以及在 C# 中设置属性的方法中哪一种最快并且使用的资源更少。

假设类TestClass有一个名为 的字符串属性Info

var instantiatedClass = new TestClass();
instantiatedClass.Info = "Information";
Run Code Online (Sandbox Code Playgroud)

或者

var instantiatedClass = new TestClass {
    Info = "Information"
}
Run Code Online (Sandbox Code Playgroud)

当然,我想知道当您必须设置 10 多个属性时哪个最快。以上只是为了说明。

谢谢

(如果本文有更好的地方,请评论)

Nik*_*wal 5

第二个片段只是语法糖。在幕后,编译器的一切都是一样的,因为它生成几乎相同的 IL 代码。

因此,使用什么代码并不重要,最终结果(就性能而言)将保持不变。

第一段 IL 代码

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       20 (0x14)
  .maxstack  2
  .locals init ([0] class SO.TestClass instantiatedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void SO.TestClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "Information"
  IL_000d:  callvirt   instance void SO.TestClass::set_Info(string)
  IL_0012:  nop
  IL_0013:  ret
} // end of method Program::Main
Run Code Online (Sandbox Code Playgroud)

第二个代码片段 IL 代码

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       20 (0x14)
  .maxstack  3
  .locals init ([0] class SO.TestClass instantiatedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void SO.TestClass::.ctor()
  IL_0006:  dup
  IL_0007:  ldstr      "Information"
  IL_000c:  callvirt   instance void SO.TestClass::set_Info(string)
  IL_0011:  nop
  IL_0012:  stloc.0
  IL_0013:  ret
} // end of method Program::Main
Run Code Online (Sandbox Code Playgroud)