string、stringbuffer、stringbuild的時間性能對比
新手,請不要噴!謝謝!
public static void main(String[] args) {
//stringbuffer是線程安全的,運行速度快於string,慢於stringbuild,考慮到運行速度快慢選stringbuild,考慮到安全問題用stringbuffer,為何stringbuffer這個看源碼吧,很簡單的一個單詞,區別了stringbuffer和stringbuild,和運用場景
//檢測string的運行速度
String str = "0123456789";
int count = 100000;
String str2 = "";
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
str2 += str;
}
long end = System.currentTimeMillis();
long time = (end - start);
System.out.println("string速度:"+time);
//檢測stringbuffere的運行速度
StringBuffer stringBuffer = new StringBuffer();
Long start1 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
stringBuffer.append(str);
}
Long endtime = System.currentTimeMillis();
long time1 = endtime-start1;
System.out.println("stringbuffer速度:"+time1);
//檢測stringbuild速度
StringBuilder stringBuilder = new StringBuilder();
long startbuild = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
stringBuilder.append(str);
}
long endStringbuild = System.currentTimeMillis();
long timebuild = endStringbuild- startbuild;
System.out.println("stringbuild速度:"+timebuild);
}
}
打印:
string速度:38545
stringbuffer速度:2
stringbuild速度:2
看出來了吧,這裏我就不解釋了!
string、stringbuffer、stringbuild的時間性能對比