Problem a.

There is a programming specification in the Ali protocol:

Avoid using an object reference to a class to access static variables or static methods that add to compiler resolution costs. Instead, use the class nameCopy the code

You can’t help but wonder what the cost would be if you referenced a static variable or static method of this class through an object

Reason 2.

I found some blogs on the Internet, and some of them said, because new object, so consumption of memory?? EXM? Check out the following demo:

public class Test {

    public static int a = 0;

    public void setA(a) {
        this.a = 1;
        // Test.a = 1;}}Copy the code

I’m thinking of a static variable in an object that is accessed by this, so there is no such thing as new or new. So what’s the difference between this.a and test. a

  • Parse the bytecode and compare:

On the left is the Code for this.a, and on the right is the Code for test. a. The difference is in the Code property sheet, which is used to store method Code. The aload_0 directive pushes the first local variable of reference type to the top of the stack, and the pop directive pops the top value of the stack. The only reference type here is this, so the thread should push this, and then access the object this points to.

  • The memory layout of Java objects

Object header: includes hashcode, GC generational age, lock status identifier, thread-held lock, biased thread ID, biased timestamp, and so on. There are also type Pointers, which are Pointers to the metadata of an object’s class

Instance data: The valid information that an object actually stores

Aligned padding: placeholder action

  • JVM memory layout – Method area

The method area, like the Java heap, is an area of memory shared by each thread. It is used to store data such as class information loaded by the virtual machine, constants, static variables, and even code compiled by the compiler

In combination with the above, it can be seen that this.a accesses the object by reference, accesses the class meta information through the object, and finally accesses the static variable.