Java 中的字串池

Sheeraz Gul 2022年5月1日
Java 中的字串池

字串池是 Java 堆中的一個儲存區域。它是 Java 虛擬機器儲存字串的特殊記憶體區域。

本教程解釋並演示了 Java 中的字串池。

Java 中的字串池

字串池用於提高效能並減少記憶體開銷。

字串分配對時間和記憶體的成本很高,因此 JVM 在初始化字串的同時執行一些操作以降低這兩種成本。這些操作是使用字串池執行的。

每當一個字串被初始化時,Java 虛擬機器都會首先檢查池,如果初始化的字串已經存在於池中,它會返回一個對池化例項的引用。如果初始化的字串不在池中,則會在池中建立一個新的字串物件。

下圖演示了 Java 堆中字串池的概覽。

Java 中的字串池

這是字串池如何工作的分步過程;讓我們以上面的圖片為例。

當類被載入時,Java 虛擬機器開始工作。

  1. JVM 現在將查詢 Java 程式中的所有字串文字。
  2. 首先,JVM 找到字串變數 d1,它具有字面量 Delftstack1; JVM 將在 Java 堆記憶體中建立它。
  3. JVM 在字串常量池記憶體中放置對文字 Delfstack1 的引用。
  4. JVM 然後尋找其他變數;如上圖所示,它會找到帶有文字 Delfstack2d2 和帶有與 d1 相同文字的 d3,即 Delftstack1
  5. 現在,字串 d1d3 具有相同的文字,因此 JVM 會將它們引用到字串池中的同一物件,從而為另一個文位元組省記憶體。

現在讓我們執行 Java 程式,演示圖中描述的示例和過程。參見示例:

package Delfstack;

public class String_Pool{
    public static void main(String[] args){
        String d1 = "Delftstack1";
        String d2 = "Delftstack2";
        String d3 = "Delftstack1";

        if(d1==d2) {
        	System.out.println("Both Strings Refers to the same object in the String Pool");
        }
        else {
        	System.out.println("Both Strings Refers to the different objects in the String Pool");
        }

        if(d1==d3) {
        	System.out.println("Both Strings Refers to the same object in the String Pool");
        }
        else {
        	System.out.println("Both Strings Refers to the different objects in the String Pool");
        }

    }
}

此程式碼將與圖片中的示例完全相同,併為三個變數建立兩個物件。見輸出:

Both Strings Refers to the different objects in the String Pool
Both Strings Refers to the same object in the String Pool
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - Java String