I've answered this but I do not know where, going to a more specific one.
In this example, has an example that there is a significant semantic change and the code will give different results .
But speaking of cost makes no difference. First, the variable space only exists for it. In the variable is reserved enough space to fit the data of its type and nothing else, no matter how many times it is modified or where or how it was declared, there is only that space.
As a side note, if the variable is by egress, each new assignment is likely to generate a new object, otherwise it is meaningless, and this will swell the heap and put pressure on the GC, which does not is ideal, but if you need to assign new objects you have nothing to do.
From the processing point of view it also makes no difference, the variable declaration is what we call no-op . So declaring out does not bring gains because the cost of declaring in is also zero.
The declaration of the variable in the background occurs at the beginning of the stack frame , that is, when a scope begins all the necessary space is reserved at once, no matter where it was declared. You can change the time of the reservation, but only once. The declaration of all variables of that new scope occurs with a change of pointer ( stack pointer ), does not even matter if it is a variable or thousands of them, the cost is the same, there is only one change in SP.
Allocation always has a cost, unless the compiler can determine that it can be deleted. And the example code has a chance of even occurring since you are doing the same thing and I think you can prove that it does not make sense to reassign the same value without stopping, so that code could be written as
int x = 10;
int y = 30;
int z = x + y;
Actually the compiler does not:
//reservando espaço para as variáveis
.locals init (
IL_0000: ldc.i4.s 10
IL_0002: ldc.i4.s 30
IL_0006: br.s IL_0000
See how was the SharpLab . Even that generates exactly the same code.
But the JITter does even more since nothing is used, it eliminates almost all the code leaving only the movement of the stack frame and loop in the same place:
L0000: push ebp //protege o BP
L0001: mov ebp, esp //só move o SP para o Base Pointer
L0003: jmp L0103 //fica repetindo sem parar
See the SharpLab .