Variables | optimization
Java programs contain a large number of objects, we need to understand where they are accessed, and where the variables are stored can have a significant effect on the performance of the program-especially if some variables need to be accessed frequently.
We write a Java class in which local variables or objects that are defined in their internal methods are stored in stack (stack), and the JVM is a stack-based, so the best performance is to access and manipulate the data in the stack. The instance variables of the Java class (the field of this class) and the static variables are stored and accessed in constant pool (Chang). All the symbolic references (symbolic references) are saved in the constant pool, pointing to all types (types), the range (field), and all functions (mothods) used by each type. When accessing instance and static variables, the JVM needs to access them by using more time-consuming opcode (which the analyst generates bytecode can see) because they are stored in constant pool.
Here's a code example that shows how to use stack variables as much as possible:
Package test;
public class Stackvars {
private int x; Instance variable
private static int staticx; Static variable
public void stackaccess (int val) {//access and Operation Stack variable J
int j = 0;
for (int i = 0; i < val; i++) {
j + + 1;
}
}
public void instanceaccess (int val) {//access and operation instance variable x
for (int i = 0; i < val; i++) {
x + 1;
}
}
public void staticaccess (int val) {//access and operation static variable Staticx
for (int i = 0; i < val; i++) {
Staticx + 1;
}
}
}
After testing, it was found that the time to run the instanceaccess () and Staticaccess () methods was about the same, but it was 2~3 times slower than running the Stackaccess () method. So we've made the following adjustments to the code for the Instanceaccess (), Staticaccess () Two methods for faster performance:
public void instanceaccess (int val) {//access and operation instance variable x
int tempx=x;
for (int i = 0; i < val; i++) {
TEMPX + 1;
}
X=TEMPX;
}
public void staticaccess (int val) {//access and operation static variable Staticx
int tempstaticx=staticx;
for (int i = 0; i < val; i++) {
Tempstaticx + 1;
}
Staticx=tempstaticx;
}
The improvement is to put the instance and static variables outside the loop, and use a stack variable to complete the local operation, and finally return the value of this stack variable back to instance or static variables, thereby improving the performance of the code.
Welcome to the comments.