Variables
Local
(temporary) variables and method-argument variables are the fastest
variables to access and update. Local variables remain on the stack,
so they can be manipulated directly; the manipulation of local
variables depends on both the VM and underlying machine
implementation. Heap variables (static and instance
variables) are manipulated in heap memory through the Java
VM-assigned bytecodes that apply to these variables. There are
special bytecodes for accessing the first four local variables and
parameters on a method stack. Arguments are counted first; then, if
there are less than four passed arguments, local variables are
counted. For nonstatic methods, this
always takes
the first slot. long
s and
double
s each take two slots. Theoretically, this
means that methods with no more than three parameters and local
variables combined (four for static
methods)
should be slightly faster than equivalent methods with a larger
number of parameters and local variables. This also means that any
variables allocated the special bytecodes should be slightly faster
to manipulate. In practice, I have found any effect is small or
negligible, and it is not worth the effort involved to limit the
number of arguments and
variables.
Instance and static variables can be up to an order of magnitude slower to operate on when compared to method arguments and local variables. You can see this clearly with a simple test comparing local and static loop counters:
package tuning.exception; public ...
Get Java Performance Tuning now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.