日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

字符串拼接方式

發布時間:2023/12/3 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 字符串拼接方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉載自?java提高篇之字符串

對于字符串而言我們經常是要對其進行拼裝處理的,在java中提高了三種拼裝的方法:+、concat()以及append()方法。這三者之間存在什么區別呢?先看如下示例:

public class StringTest {/*** @desc 使用+、concat()、append()方法循環10W次* @author chenssy* @data 2013-11-16* @param args* @return void*/public static void main(String[] args) {//+long start_01 = System.currentTimeMillis();String a = "a";for(int i = 0 ; i < 100000 ; i++){a += "b";}long end_01 = System.currentTimeMillis();System.out.println(" + 所消耗的時間:" + (end_01 - start_01) + "毫米");//concat()long start_02 = System.currentTimeMillis();String c = "c";for(int i = 0 ; i < 100000 ; i++){c = c.concat("d");}long end_02 = System.currentTimeMillis();System.out.println("concat所消耗的時間:" + (end_02 - start_02) + "毫米");//appendlong start_03 = System.currentTimeMillis();StringBuffer e = new StringBuffer("e");for(int i = 0 ; i < 100000 ; i++){e.append("d");}long end_03 = System.currentTimeMillis();System.out.println("append所消耗的時間:" + (end_03 - start_03) + "毫米");} } Output: ??+?? 所消耗的時間:19080毫米 concat所消耗的時間:9089毫米 append所消耗的時間:10毫米

從上面的運行結果可以看出,append()速度最快,concat()次之,+最慢。原因請看下面分解:

(1)+方式拼接字符串

在前面我們知道編譯器對+進行了優化,它是使用StringBuilder的append()方法來進行處理的,我們知道StringBuilder的速度比StringBuffer的速度更加快,但是為何運行速度還是那樣呢?主要是因為編譯器使用append()方法追加后要同toString()轉換成String字符串,也就說? str +=”b”等同于

str = new StringBuilder(str).append(“b”).toString();

它變慢的關鍵原因就在于new StringBuilder()和toString(),這里可是創建了10W個StringBuilder對象,而且每次還需要將其轉換成String,速度能不慢么?

(2)concat()方法拼接字符串

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);}

這是concat()的源碼,它看上去就是一個數字拷貝形式,我們知道數組的處理速度是非常快的,但是由于該方法最后是這樣的:return new String(0, count + otherLen, buf);這同樣也創建了10W個字符串對象,這是它變慢的根本原因。

(3)append()方法拼接字符串

public synchronized StringBuffer append(String str) {super.append(str);return this;}

StringBuffer的append()方法是直接使用父類AbstractStringBuilder的append()方法,該方法的源碼如下:

public AbstractStringBuilder append(String str) {if (str == null) str = "null";int len = str.length();if (len == 0) return this;int newCount = count + len;if (newCount > value.length)expandCapacity(newCount);str.getChars(0, len, value, count);count = newCount;return this;}

與concat()方法相似,它也是進行字符數組處理的,加長,然后拷貝,但是請注意它最后是返回并沒有返回一個新串,而是返回本身,也就說這這個10W次的循環過程中,它并沒有產生新的字符串對象。

通過上面的分析,我們需要在合適的場所選擇合適的字符串拼接方式,但是并不一定就要選擇append()和concat()方法,原因在于+根據符合我們的編程習慣,只有到了使用append()和concat()方法確實是可以對我們系統的效率起到比較大的幫助,才會考慮,同時鄙人也真的沒有怎么用過concat()方法。

總結

以上是生活随笔為你收集整理的字符串拼接方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。