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
}
}
All else being equal (and they usually aren’t, which is why you normally have to actually test it),
ONE()andTWO()should generate the same IL instructions since local variables end up scoped to the whole method.THREE()will be negligibly slower ifx==10since 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.