Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

performance

c#

I have a code where I'm declaring an object inside a loop, like:

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

Will there be any performance gain if I modify the code as follows:

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

Thanks in advance.

like image 250
Derin Avatar asked Mar 02 '11 11:03

Derin


3 Answers

There is no performance gain as such. It only helps the variable to go out of scope later than sooner.

like image 144
Sachin Shanbhag Avatar answered Nov 03 '22 20:11

Sachin Shanbhag


The compiler will automatically optimize the code to move the declaration outside the loop anyway, so there is nothing to gain by doing this.

For example

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

Will be optimized be the compiler into this

int i;
while(...){
  i = 5;
  ...
}
like image 3
Øyvind Bråthen Avatar answered Nov 03 '22 20:11

Øyvind Bråthen


The actual object allocation happens with clA = new ClassA(); so unless you can move it out of the loop you won't get any performance gain.

like image 1
Albireo Avatar answered Nov 03 '22 18:11

Albireo