There are several memory areas in Java (and other languages) that are used for various tasks.
The most expensive one is the heap memory, basically everything created using the new
keyword goes to the heap.
Then there is the Stack, a local "heap" so to speak, but without most of the cost associated with the creation of heap variables and therefore much faster. Almost all local variables like updateWords
are located in the stack.
Registers are processor internal variables that are lightning fast. The JVM optimizer will always try to put things into internal registers whenever they fit, but since the amount of registers is very limited, only very frequently used variables go there.
But expensive means something like 0.0000000001 seconds of execution time difference between heap and register.
Then you should know what you are actually reserving when declaring a local String or any Object: a pointer. Effectively a 32/64 bit "integer" that holds the address of where to actually find the String/Object. So the instruction String updateWords = updateAuto();
will not create a new string nor copy it anywhere, all that happens is that the updateAuto() function returns a pointer ("integer") and updateWords is set to that value. This is as fast as writing int updateWords = 42
and completely done on the stack or even the register if the optimizer feels like.
Usually you should worry much more about visibility and what is most convenient/produces the least errors for your application than how the memory is organized internally. For once hand-optimization usually increases your application speed by no more than 0.0000001% and second the only stupid thing to do when reserving memory is to do it pointlessly in a loop like this:
for (int i = 0; i < 1000; ++i) {
new MyReallyStupidMemoryWastingObject();
}
But even that is handled gracefully by the Garbage Collector (as long as you do not save all those pointers by putting them in a list or something like that).
Therefore: use globals if that simplifies your code and especially reduces bugs. Examples are global constants like enumerations or widely used string keywords. Otherwise use local or class-local variables and rely on the JVM to do things properly.
One common thing is to give the JVM a usage hint with the word final
. This allows the JVM to do full optimizations on this variable, even completely removing it by putting it into a register, because it knows that you will never change it.