探秘Java中String、StringBuilder以及StringBuffer

来源:http://www.cnblogs.com/8hao/archive/2016/03/01/5230651.html
-Advertisement-
Play Games

相信String這個類是Java中使用得最頻繁的類之一,並且又是各大公司面試喜歡問到的地方,今天就來和大家一起學習一下String、StringBuilder和StringBuffer這幾個類,分析它們的異同點以及瞭解各個類適用的場景。下麵是本文的目錄大綱: 一.你瞭解String類嗎? 二.深入理


相信String這個類是Java中使用得最頻繁的類之一,並且又是各大公司面試喜歡問到的地方,今天就來和大家一起學習一下String、StringBuilder和StringBuffer這幾個類,分析它們的異同點以及瞭解各個類適用的場景。下麵是本文的目錄大綱:

一.你瞭解String類嗎?

二.深入理解String、StringBuffer、StringBuilder

三.不同場景下三個類的性能測試

四.常見的關於String、StringBuffer的面試題(闢謠網上流傳的一些曲解String類的說法)

若有不正之處,請多多諒解和指正,不勝感激。

一.你瞭解String類嗎?

想要瞭解一個類,最好的辦法就是看這個類的實現源代碼,String類的實現在

\jdk1.6.0_14\src\java\lang\String.java   文件中。

打開這個類文件就會發現String類是被final修飾的:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public final class String     implements java.io.Serializable, Comparable<String>, CharSequence {     /** The value is used for character storage. */     private final char value[];       /** The offset is the first index of the storage that is used. */     private final int offset;       /** The count is the number of characters in the String. */     private final int count;       /** 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;       ......   }

從上面可以看出幾點:

1)String類是final類,也即意味著String類不能被繼承,並且它的成員方法都預設為final方法。在Java中,被final修飾的類是不允許被繼承的,並且該類中的成員方法都預設為final方法。在早期的JVM實現版本中,被final修飾的方法會被轉為內嵌調用以提升執行效率。而從Java SE5/6開始,就漸漸擯棄這種方式了。因此在現在的Java SE版本中,不需要考慮用final去提升方法調用效率。只有在確定不想讓該方法被覆蓋時,才將方法設置為final。

2)上面列舉出了String類中所有的成員屬性,從上面可以看出String類其實是通過char數組來保存字元串的。

下麵再繼續看String類的一些方法實現:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 public String substring(int beginIndex, int endIndex) {     if (beginIndex < 0) {         throw new StringIndexOutOfBoundsException(beginIndex);     }     if (endIndex > count) {         throw new StringIndexOutOfBoundsException(endIndex);     }     if (beginIndex > endIndex) {         throw new StringIndexOutOfBoundsException(endIndex - beginIndex);     }     return ((beginIndex == 0) && (endIndex == count)) ? this :         new String(offset + beginIndex, endIndex - beginIndex, value);     }    public String concat(String str) {     int otherLen = str.length();     if (otherLen == 0) {         return this;     }     char buf[] = new char[count + otherLen];     getChars(0, count, buf, 0);     str.getChars(0, otherLen, buf, count);     return new String(0, count + otherLen, buf);     }    public String replace(char oldChar, char newChar) {     if (oldChar != newChar) {         int len = count;         int i = -1;         char[] val = value; /* avoid getfield opcode */         int off = offset;   /* avoid getfield opcode */           while (++i < len) {         if (val[off + i] == oldChar) {             break;         }         }         if (i < len) {         char buf[] = new char[len];         for (int j = 0 ; j < i ; j++) {             buf[j] = val[off+j];         }         while (i < len) {             char c = val[off + i];             buf[i] = (c == oldChar) ? newChar : c;             i++;         }         return new String(0, len, buf);         }     }     return this;
 

從上面的三個方法可以看出,無論是sub操、concat還是replace操作都不是在原有的字元串上進行的,而是重新生成了一個新的字元串對象。也就是說進行這些操作後,最原始的字元串並沒有被改變。

在這裡要永遠記住一點:

“對String對象的任何改變都不影響到原對象,相關的任何change操作都會生成新的對象”。

在瞭解了於String類基礎的知識後,下麵來看一些在平常使用中容易忽略和混淆的地方。

二.深入理解String、StringBuffer、StringBuilder

1.String str=”hello world”和String str=new String(“hello world”)的區別

想必大家對上面2個語句都不陌生,在平時寫代碼的過程中也經常遇到,那麼它們到底有什麼區別和聯繫呢?下麵先看幾個例子:

1 2 3 4 5 6 7 8 9 10 11 12 13 public class Main {       public static void main(String[] args) {         String str1 = "hello world";         String str2 = new String("hello world");         String str3 = "hello world";         String str4 = new String("hello world");           System.out.println(str1==str2);         System.out.println(str1==str3);         System.out.println(str2==str4);     } }
 

這段代碼的輸出結果為

為什麼會出現這樣的結果?下麵解釋一下原因:

在前面一篇講解關於JVM記憶體機制的一篇博文中提到 ,在class文件中有一部分 來存儲編譯期間生成的 字面常量以及符號引用,這部分叫做class文件常量池,在運行期間對應著方法區的運行時常量池。

因此在上述代碼中,String str1 = “hello world”;和String str3 = “hello world”; 都在編譯期間生成了 字面常量和符號引用,運行期間字面常量”hello world”被存儲在運行時常量池(當然只保存了一份)。通過這種方式來將String對象跟引用綁定的話,JVM執行引擎會先在運行時常量池查找是否存在相同的字面常量,如果存在,則直接將引用指向已經存在的字面常量;否則在運行時常量池開闢一個空間來存儲該字面常量,並將引用指向該字面常量。

總所周知,通過new關鍵字來生成對象是在堆區進行的,而在堆區進行對象生成的過程是不會去檢測該對象是否已經存在的。因此通過new來創建對象,創建出的一定是不同的對象,即使字元串的內容是相同的。

2.String、StringBuffer以及StringBuilder的區別

既然在Java中已經存在了String類,那為什麼還需要StringBuilder和StringBuffer類呢?

那麼看下麵這段代碼:

1 2 3 4 5 6 7 8 9 public class Main {       public static void main(String[] args) {         String string = "";         for(int i=0;i<10000;i++){             string += "hello";         }     } }
 

這句 string += “hello”;的過程相當於將原有的string變數指向的對象內容取出與”hello”作字元串相加操作再存進另一個新的String對象當中,再讓string變數指向新生成的對象。如果大家還有疑問可以反編譯其位元組碼文件便清楚了:

從這段反編譯出的位元組碼文件可以很清楚地看出:從第8行開始到第35行是整個迴圈的執行過程,並且每次迴圈會new出一個StringBuilder對象,然後進行append操作,最後通過toString方法返回String對象。也就是說這個迴圈執行完畢new出了10000個對象,試想一下,如果這些對象沒有被回收,會造成多大的記憶體資源浪費。從上面還可以看出:string+=”hello”的操作事實上會自動被JVM優化成:

StringBuilder str = new StringBuilder(string);

str.append(“hello”);

str.toString();

再看下麵這段代碼:

1 2 3 4 5 6 7 8 9 public class Main {       public static void main(String[] args) {         StringBuilder stringBuilder = new StringBuilder();         for(int i=0;i<10000;i++){             stringBuilder.append("hello");         }     } }
 

反編譯位元組碼文件得到:

從這裡可以明顯看出,這段代碼的for迴圈式從13行開始到27行結束,並且new操作只進行了一次,也就是說只生成了一個對象,append操作是在原有對象的基礎上進行的。因此在迴圈了10000次之後,這段代碼所占的資源要比上面小得多。

那麼有人會問既然有了StringBuilder類,為什麼還需要StringBuffer類?查看源代碼便一目瞭然,事實上,StringBuilder和StringBuffer類擁有的成員屬性以及成員方法基本相同,區別是StringBuffer類的成員方法前面多了一個關鍵字:synchronized,不用多說,這個關鍵字是在多線程訪問時起到安全保護作用的,也就是說StringBuffer是線程安全的。

下麵摘了2段代碼分別來自StringBuffer和StringBuilder,insert方法的具體實現:

StringBuilder的insert方法

1 2 3 4 5 6 public StringBuilder insert(int index, char str[], int offset,                               int len)   {       super.insert(index, str, offset, len);   return this;   }
 

StringBuffer的insert方法:

1 2 3 4 5 6 public synchronized StringBuffer insert(int index, char str[], int offset,                                             int len)     {         super.insert(index, str, offset, len);         return this;     }
 

三.不同場景下三個類的性能測試

從第二節我們已經看出了三個類的區別,這一小節我們來做個小測試,來測試一下三個類的性能區別:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 public class Main {     private static int time = 50000;     public static void main(String[] args) {         testString();         testStringBuffer();         testStringBuilder();         test1String();         test2String();     }       public static void testString () {         String s="";         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             s += "java";         }         long over = System.currentTimeMillis();         System.out.println("操作"+s.getClass().getName()+"類型使用的時間為:"+(over-begin)+"毫秒");     }       public static void testStringBuffer () {         StringBuffer sb = new StringBuffer();         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             sb.append("java");         }         long over = System.currentTimeMillis();         System.out.println("操作"+sb.getClass().getName()+"類型使用的時間為:"+(over-begin)+"毫秒");     }       public static void testStringBuilder () {         StringBuilder sb = new StringBuilder();         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             sb.append("java");         }         long over = System.currentTimeMillis();         System.out.println("操作"+sb.getClass().getName()+"類型使用的時間為:"+(over-begin)+"毫秒");     }       public static void test1String () {         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             String s = "I"+"love"+"java";         }         long over = System.currentTimeMillis();         System.out.println("字元串直接相加操作:"+(over-begin)+"毫秒");     }       public static void test2String () {         String s1 ="I";         String s2 = "love";         String s3 = "java";         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             String s = s1+s2+s3;         }         long over = System.currentTimeMillis();         System.out.println("字元串間接相加操作:"+(over-begin)+"毫秒");     }   }
 

測試結果(win7,Eclipse,JDK6):

上面提到string+=”hello”的操作事實上會自動被JVM優化,看下麵這段代碼:

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • MVVMlight在UWP開發中的使用
  • 在ASP.NET2.0開始,提供了母版頁的功能。母版頁由一個母版頁和多個內容頁構成。母版頁的主要功能是為ASP.NET應用程式中的頁面創建相同的佈局和界面風格。母版頁的使用與普通頁面類似,可以在其中放置文件或者圖形、任何HTML控制項和Web控制項、後置代碼等。 母版頁僅僅是一個頁面模板,單獨的母版頁是
  • 繼續,前面已經實現了C#調用Windows API實現了彈出對話框功能。使用了User32.dll文件,主要代碼如下:[DllImport("User32.dll")]public static extern int MessageBox(int h, string m, string c, int
  • 以下為本次實踐代碼: 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Linq; 5 using System.Reflection; 6 using
  • 最近項目中有用到Webservice,研究了Spring與CXF整合的官方文檔(其實官方文檔說的清楚了,建議大伙還是看官方文檔,都是很簡單英文單詞),所以就有了下麵的demo,相信大伙都能看懂 用的主要架構為Maven + Spring + CXF + IDEA,廢話就不多說了,先看下整個個項目結構...
  • Jetty是一個用 Java 實現、開源、基於標準的,並且具有豐富功能的 Http 伺服器和 Web 容器。Jetty中應用最廣泛的一項功能就是可以作為嵌入式Web容器。 在開發階段,可以使用Jetty在Eclipse里直接啟動應用,而不是像Tomcat那樣繁瑣,先把幾十兆應用打包,然後再複製到某個
  • 因為公司項目線上人數的增加,隨著現在硬體成本越來越低,大多數的生產環境記憶體大多都已經達到 16G,尤其最新的阿裡雲,客戶的機器都是配置超高的java主機,但是Java的運行環境,記憶體使用有限 ,這樣就造成了這台伺服器資源的浪費,所以單機的多Tomcat集群就很有必要!當然有客戶有多台伺服器,這樣更好
  • 首先純html頁要用meta標簽聲明編碼<meta http-equiv="Content-Type" content="text/html; charset="utf-8" />有php輸出的頁要使用header函數聲明編碼header("Content-Type:text/html; chars
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class Main {     private static int time = 50000;     public static void main(String[] args) {         testString();         testOptimalString();     }       public static void testString () {         String s="";         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             s += "java";         }         long over = System.currentTimeMillis();         System.out.println("操作"+s.getClass().getName()+"類型使用的時間為:"+(over-begin)+"毫秒");     }       public static void testOptimalString () {         String s="";         long begin = System.currentTimeMillis();         for(int i=0; i<time; i++){             StringBuilder sb = new StringBuilder(s);             sb.append("java");             s=sb.toString();         }         long over = System.currentTimeMillis();         System.out.println("模擬JVM優化操作的時間為:"+(over-begin)+"毫秒");     }   }