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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With