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

What is the fastest way to create new model and set properties in C#?

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

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

var instantiatedClass = new TestClass();
instantiatedClass.Info = "Information";

var instantiatedClass = new TestClass {
    Info = "Information"
}

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

谢谢

(如果post中有任何更好的地方请评论)

第二个片段只是语法糖。在幕后,它对于编译器来说都是一样的,因为它生成几乎相同的 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

第二个代码片段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