Is there any performance gain by declaring an object outside the loop

I have code in which I declare an object inside a loop, for example:

foreach(...)
{
ClassA clA = new ClassA();
clA.item1=1;
clA.item2=2;
ClassB.Add(clA);
}

Will there be any performance increase if I change the code as follows:

ClassA clA;
foreach(...)
{
clA = new ClassA();
clA.item1=1;
clA.item2=2;
ClassB.Add(clA);
}

Thanks in advance.

+5
source share
4 answers

There is no performance in this. This only helps the variable get out of scope later than before.

+4
source

The compiler automatically optimizes the code to move the ad outside the loop anyway, so nothing can be done.

for instance

while(...){
  int i = 5;
  ...
}

The compiler will be optimized in this

int i;
while(...){
  i = 5;
  ...
}
+3
source

The actual distribution of objects occurs with clA = new ClassA();, so if you cannot get it out of the loop, you will not get any performance increase.

+1
source

As everyone said, actually, but I would still change my code to:

foreach(...)
{
ClassB.Add(new ClassA() { item1=1, item2=2 });
}
+1
source

All Articles