简体   繁体   中英

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

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.

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

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;
  ...
}

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.

As everyone's said, not really, but I'd still change your code to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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