速度的快慢,用實驗來說話,(針對100000個随機字元)如圖:
1.首先是運作速度:StringBuilder > StringBuffer > String
Java中對String對象進行的操作實際上是一個不斷建立新的對象并且将舊的對象回收的一個過程,是以執行速度很慢,而StringBuilder和StringBuffer的對象是變量,對變量進行操作就是直接對該對象進行更改,而不進行建立和回收的操作,是以速度要比String快很多
2.安全程度:StringBuilder是線程不安全的,而StringBuffer是線程安全的
參考其他人部落格,StringBuffer對象在字元串緩沖區被多個線程使用時,StringBuffer中很多方法可以帶有synchronized關鍵字,是以可以保證線程是安全的,但StringBuilder的方法則沒有該關鍵字,是以不能保證線程安全,有可能會出現一些錯誤的操作。是以如果要進行的操作是多線程的,那麼就要使用StringBuffer,但是在單線程的情況下,還是建議使用速度比較快的StringBuilder。
3.結論
String:适用于少量的字元串操作
測試代碼:
public static void main(String[] args) {
stringTest();
stringBufferTest();
stringBuilderTest();
}
private static void stringBuilderTest() {
long start = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append((char)Math.floor(Math.random()*(90-65+1)+65));
}
long end = System.currentTimeMillis();
System.out.println("StringBuilder 對于100000個随機字元的測試時間為:" + (end-start));
}
private static void stringBufferTest() {
long start = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 100000; i++) {
sb.append((char)Math.floor(Math.random()*(90-65+1)+65));
}
long end = System.currentTimeMillis();
System.out.println("StringBuffer 對于100000個随機字元的測試時間為:" + (end-start));
}
private static void stringTest() {
String s = null;
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
s += (char)Math.floor(Math.random()*(90-65+1)+65);
}
long end = System.currentTimeMillis();
System.out.println("String 對于100000個随機字元的測試時間為:" + (end-start));
}