In C#, would there be any difference in performance when comparing the following THREE alternatives?
ONE
void ONE(int x) {
if (x == 10)
{
int y = 20;
int z = 30;
// do other stuff
} else {
// do other stuff
}
}
TWO
void TWO(int x) {
int y;
int z;
if (x == 10)
{
y = 20;
z = 30;
// do other stuff
} else {
// do other stuff
}
}
THREE
void THREE(int x) {
int y = 20;
int z = 30;
if (x == 10)
{
// do other stuff
} else {
// do other stuff
}
}
In short, you are right to do it. Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time.
If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.
In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure. A loop variable is a classical fixture in programming that helps computers to handle repeated instructions.
All else being equal (and they usually aren't, which is why you normally have to actually test it), ONE()
and TWO()
should generate the same IL instructions since local variables end up scoped to the whole method. THREE()
will be negligibly slower if x==10
since the other two won't bother to store the values in the local variables.
All three take up the same amount of memory—the memory for all variables is allocated even if nothing is stored in them. The JIT compiler may perform an optimization here, though, if it ever looks for unused variables.
There no performance difference, but you're going to find variable scope issues between each of those examples.
You're also showing three different intents between those examples, which isn't what you want:
y and z are limited to the scope of the if statement.
y and z are used outside of the if statement, but are set conditionally.
y and z have nothing to do with the if statement whatsoever.
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