標籤:string stringbuffer
首先闡述String類和StringBuffer類的區別,String類是常量,不能添加,而StringBuffer則是一個字元緩衝區,可以往裡面添加字串。比如說:
<span style="font-size:18px;">String str = "helloworld";str += "welcome";</span>
這裡其實過程是這樣的:產生了String對象 "helloworld" 引用由str持有, 當執行 str += "welcome" ; 這行代碼的時候其實是廢棄了 原來的 "helloworld"對象 然後產生了新的拼接之後的對象,然後把引用賦給了str。 所以過程中又產生了新的String類型的對象,然後原來的對象就要被記憶體回收行程回收。肯定是要影響程式的效能。
那麼,我們現在再來看一看StringBuffer的做法
<span style="font-size:18px;">StringBuffer sb = new StringBuffer("helloworld");sb.append("welcome");</span>
StringBuffer的過程是這樣的。首先構造出一個StringBuffer對象,在緩衝區中,讓後可以在緩衝區中直接添加指定的字串序列。
還有一種寫法肯定是錯的 :
StringBuffer sb = new StringBuffer();
sb = "helloworld"; //字串對象怎麼能賦給StringBuffer對象呢?
然後下面的測試String 類和StringBuffer類的效能測試程式碼片段
執行效果不絕對,因每一台機子的硬體設定而定。
首先是String類的效能
<span style="font-size:18px;">/* 本程式碼片段測試String類的效能 約2854毫秒String tempValue = "helloworld"; int times = 10000;String value = "";long startTime = System.currentTimeMillis();for(int i = 0 ;i < times ; i++){value += tempValue;}long endTime = System.currentTimeMillis();System.out.println(endTime - startTime);*/</span>
然後是StringBuffer類
<span style="font-size:18px;">/* 本程式碼片段用於測試StringBuffer類的效能 約為10毫秒String tempValue = "helloworld";int times = 10000;StringBuffer sb = new StringBuffer();long startTime = System.currentTimeMillis();for(int i = 0 ; i < times ; i++){sb.append(tempValue);}long endTime = System.currentTimeMillis();System.out.println(endTime - startTime);*/</span>
在一個就是StringBuilder 和StringBuffer類的比較
怎麼說的StringBuilder類是從JDK5.0開始出現的類。用來替代StringBuffer 。但是不保證安全執行緒。如果你需要這種同步,請使用StringBuffer類,StringBuilder類是線程不安全的。而StringBuffer是安全執行緒的。
效能上來說StringBuilder是比StringBuffer的效能要強那麼一點點,但是兩個類總體上的使用方法是差不多的。
一下是測試StringBuilder類的效能的測試程式碼片段。
<span style="font-size:18px;">/* 本程式碼片段用於測試 StringBuilder類的效能 約10毫秒String tempValue = "helloworld";int times = 10000;StringBuilder sb = new StringBuilder();long startTime = System.currentTimeMillis();for(int i = 0 ; i < times ; i++){sb.append(tempValue);}long endTime = System.currentTimeMillis();System.out.println(endTime - startTime);*/</span>
綜上所述:如果你使用的是常量的要多一些,還請使用String類 ,如果經常改變值,還請使用StringBuffer 或StringBuilder。
一般來說效能上 StringBuilder > StringBuffer > String
Java中String類StringBuffer類和StringBuilder類的區別