I have a code where I'm declaring an object inside a loop, like:
for开发者_C百科each(...)
{
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 });
}
精彩评论