How much memory space does String in Java take up? Take you step by step verification!

Write in front

Recently I always ask a question: How much memory space does the String class in Java occupy? Many of my friends’ answers really made me dumbfounded. Some said they didn’t take up space, some said 1 byte, some said 2 bytes, some said 3 bytes, some said they didn’t know, and some said they don’t know. What is dumbfounding is that some people say it is 2 to the 31st power. If this is the case, the server's memory space still cannot fit a string! As programmers, we can't make such a joke. Today, let's talk about how much memory space the String in Java occupies!

Friends who need more Java knowledge and interview questions can click the link below to get it for free

Link: 1103806531 Password: CSDN

Insert picture description here

The structure of Java objects

First, let's take the structure of the Java object in the virtual machine. Here, take the HotSpot virtual machine as an example.

Insert picture description here
As can be seen from the above picture, the structure of the object in memory mainly includes the following parts:

  • Mark Word (mark field): The Mark Word part of the object occupies 4 bytes, and its content is a series of mark bits, such as the mark bits of the lightweight lock, the mark bits of the bias lock, and so on.
  • Klass Pointer (Class object pointer): The size of the Class object pointer is also 4 bytes, and the location it points to is the memory address of the corresponding Class object (its corresponding metadata object)
  • The actual data of the object: it includes all the member variables of the object, and its size is determined by the size of each member variable, for example: byte and boolean are 1 byte, short and char are 2 bytes, int and float are 4 Byte, long and double are 8 bytes, reference is 4 bytes
  • Alignment: The last part is to align the filled bytes, which are filled with 8 bytes.

In other words:

  • Object header: 8 bytes (save the object's class information, ID, state in the virtual machine)
  • Java primitive data: such as int, float, char and other types of data
  • Reference: 4 bytes
  • Padding

String type in Java

Space occupied by empty String

Here, we take Java8 as an example to illustrate. First, let's look at the member variables in the String class.

/** The value is used for character storage. */
private final char value[];
 
/** Cache the hash code for the string */
private int hash; // Default to 0
 
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;

Arrays are also objects in Java, so arrays also have object headers. Therefore, the space occupied by an array is the space occupied by the object header plus the array length plus the array reference, that is, 8 + 4 + 4 = 16 bytes.

So, we can get the memory space occupied by an empty String object, as shown below.

对象头(8 字节)+ 引用 (4 字节 )  + char 数组(16 字节)+ 1int4字节)+ 1long8字节)= 40 字节

So, my friends, are your answers correct?

Space occupied by non-empty String

If the length of the String string is greater than 0, we can also get the calculation formula for the memory occupied by String, as shown below.

40 + 2 * n

Among them, n is the length of the string.

Here, some friends may ask, why is it 40 + 2 n? This is because 40 is the memory space occupied by an empty string. As we have already said above, the String class actually stores data in the char[] member variable array, and a char type in the char[] array The data occupies 2 bytes of space, so just the data in the String will occupy 2 n (n is the length of the string) bytes of space, plus the 40 bytes occupied by the empty string, Finally, the storage space occupied by a string is: 40 + 2 * n (n is the length of the string).

Note: The formula 40 + 2 * n can be regarded as a general formula for calculating how much memory space the String object occupies.

Therefore, when a large number of String objects are used in the code, the actual memory usage should be considered.

Verification conclusion

Next, we will verify our above conclusions together. First, create a UUIDUtils class to generate a 32-bit UUID, as shown below.

package io.mykit.binghe.string.test;

import java.util.UUID;

/**
 * @author binghe
 * @version 1.0.0
 * @description 生成没有-的UUID
 */
public class UUIDUtils {
    
    
    public static String getUUID(){
    
    
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }
}

Next, create a TestString class, create an array with a length of 4000000 in the main() method, and then fill the array with UUID strings, as shown below.

package io.mykit.binghe.string.test;

import java.util.UUID;

/**
 * @author binghe
 * @version 1.0.0
 * @description 测试String占用的内存空间
 */
public class TestString{
    
    
    public static void main(String[] args){
    
    
         String[] strContainer = new String[4000000];
        for(int i = 0; i < 4000000; i++){
    
    
            strContainer[i] = UUIDUtils.getUUID();
            System.out.println(i);
        }
        //防止程序退出
        while(true){
    
    

        }
    }
}

Here, there are 4000000 character strings, and the length of each character string is 32, so the memory space occupied by storing the string data is: (40 + 32 2) 4000000 = 416000000 bytes, which is approximately equal to 416MB.

We use Jprofiler memory analysis tool for analysis:

Insert picture description here
As you can see, the result of using the Jprofiler memory analysis tool is: 321MB + 96632KB, which is approximately equal to 417MB. The reason why the results obtained by using the Jprofiler memory analysis tool are larger than our calculations is that during the actual running of the program, some strings will be generated inside the program, and these strings will also take up memory space! !

Therefore, the results obtained by using the Jprofiler memory analysis tool met our expectations.

At last

I have also compiled a complete set of video tutorials for architects and systematic materials on java, including java core knowledge points, interview topics, and the latest 20 years of Internet real questions and e-books. Friends in need can click the link below to get it for free!

Link: 1103806531 Password: CSDN

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/XingXing_Java/article/details/109250697