![619357124ceaa0f0149a15366728570f.png](https://i-blog.csdnimg.cn/blog_migrate/6923773875bdb7bbfb6b75002743761a.jpeg)
从文件或者键盘输入较短的单词,构建成较长的字符串,采用字符串拼接的方式效率较低。每次连接字符串,都会构建一个新的String对象,耗时且浪费空间。
StringBuilder类可以避免这个问题的发生。
如果需要许多小段的字符串构建一个字符串,首先构建一个空的字符串构建器:
StringBuilder builder = new StringBuilder();
每次需要添加一部分内容时,就调用apped方法:
builder.append(ch); //append a single character
builder.append(str); // append a string
在需要构建字符串时调用toString方法,将可以得到一个String对象:
String completeStr = builder.toString();
清空StringBuilder内容:
builder.delete(0, builder.length);
测试:
int i = 0;
final int loops = 1000;
// 测试StringBuilder构建长字符串
long sTime = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
while (i < 1000) {
String str = "";
for (int j = 0; j < loops; j++) {
sb.append("" + j);
}
str = sb.toString();
sb.delete(0, sb.length());
if (i == loops - 1) {
System.out.println(str);
}
i++;
}
long eTime = System.currentTimeMillis();
System.out.println("time is " + (eTime - sTime));
// 测试字符串拼接构建长字符串
i = 0;
long sTime1 = System.currentTimeMillis();
while (i < 1000) {
String str1 = "";
for (int j = 0; j < loops; j++) {
str1 += j;
}
if (i == loops - 1) {
System.out.println(str1);
}
i++;
}
long eTime1 = System.currentTimeMillis();
System.out.println("time1 is " + (eTime1 - sTime1));
/* 测试结果
loops = 1000 -> time: 38; time1: 30
loops = 1000 -> time: 98; time1: 607
结论:loops越大,StringBuilder优势越明显
*/