简体   繁体   English

在C#中创建类的对象时如何提高性能

[英]How in increase the performance while creating an object of a class in c#

I know its a silly question that I am about to ask, but I just want to know the difference in the below given statements: 我知道这是一个愚蠢的问题,但我只想知道以下给定陈述中的区别:

Abc object= new ABC();
object.Age=obj1.Age;
object.Place=obj1.Place;
object.Street=obj1.Street;
object.Number=obj1.Number;
object.POBox=obj1.POBox;

and

Abc object= new ABC()
{
    Age=obj1.Age,
    Place=obj1.Place,
    Street=obj1.Street,
    Number=obj1.Number,
    POBox=obj1.POBox
};

Will the above written code help in increasing performance? 以上编写的代码是否有助于提高性能? I just want to know if there is any way we can increase the performance while creating an object of a class and assigning values to that class object? 我只想知道在创建类的对象并将值分配给该类对象时,是否有任何方法可以提高性能?

No. These statements are compiled to the same IL so there is no performance improvement. 否。这些语句被编译为相同的IL,因此不会提高性能。

The first one: 第一个:

IL_0031: newobj instance void TestApplication.ABC::.ctor()
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: ldc.i4.1
IL_0039: callvirt instance void TestApplication.ABC::set_Age(int32)
IL_003e: nop
IL_003f: ldloc.1
IL_0040: ldc.i4.1
IL_0041: callvirt instance void TestApplication.ABC::set_Place(int32)
IL_0046: nop
IL_0047: ldloc.1
IL_0048: ldc.i4.1
IL_0049: callvirt instance void TestApplication.ABC::set_Street(int32)
IL_004e: nop
IL_004f: ldloc.1
IL_0050: ldc.i4.1
IL_0051: callvirt instance void TestApplication.ABC::set_Number(int32)
IL_0056: nop
IL_0057: ldloc.1
IL_0058: ldc.i4.1
IL_0059: callvirt instance void TestApplication.ABC::set_POBox(int32)

And the second one: 第二个:

IL_0001: newobj instance void TestApplication.ABC::.ctor()
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: ldc.i4.1
IL_0009: callvirt instance void TestApplication.ABC::set_Age(int32)
IL_000e: nop
IL_000f: ldloc.2
IL_0010: ldc.i4.1
IL_0011: callvirt instance void TestApplication.ABC::set_Place(int32)
IL_0016: nop
IL_0017: ldloc.2
IL_0018: ldc.i4.1
IL_0019: callvirt instance void TestApplication.ABC::set_Street(int32)
IL_001e: nop
IL_001f: ldloc.2
IL_0020: ldc.i4.1
IL_0021: callvirt instance void TestApplication.ABC::set_Number(int32)
IL_0026: nop
IL_0027: ldloc.2
IL_0028: ldc.i4.1
IL_0029: callvirt instance void TestApplication.ABC::set_POBox(int32)

I thought that there's a subtle difference: the second statement is atomic; 我认为这有一个细微的差别:第二个陈述是原子的;第二个陈述是原子的。 you can use it to make sure the object is initialized in the correct state when there is no appropriate constructor. 您可以使用它来确保在没有适当的构造函数时将对象初始化为正确的状态。

mote info: http://bartdesmet.net/blogs/bart/archive/2007/11/22/c-3-0-object-initializers-revisited.aspx 微粒信息: http : //bartdesmet.net/blogs/bart/archive/2007/11/22/c-3-0-object-initializers-revisited.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM