Do not be afraid to use local variables. The difference in memory usage and performance is very small or, in some cases, completely absent.
In your particular case, local variables can use 8 bytes (16 bytes in a 64-bit application) of the stack space. However, the compiler can create local variables on its own, if necessary for temporary storage, therefore, in either case, both versions have the same set of local variables.
In addition, the compiler can use processor registers instead of the stack space for some local variables, so itβs not even sure that creating a local variable actually uses any stack space in general.
Stack space allocation is very cheap. When a method is called, a stack stack is created for local data in the method. If you need to allocate more memory, this will only change how the stack pointer moves; it does not generate any additional code at all.
So, just write code to be robust and reliable, and trust the compiler to optimize the use of the variable.
Guffa source share