Running Rabbit
Running Rabbit

Reputation: 2720

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?

Upvotes: 0

Views: 269

Answers (2)

Denys Denysenko
Denys Denysenko

Reputation: 7894

No. These statements are compiled to the same IL so there is no performance improvement.

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)

Upvotes: 5

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

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

Upvotes: 1

Related Questions