概述
StringBuilder,StringBuffer中 没有提供clear或empty方法。 清空有3种方法: 1)新生成一个,旧的由系统自动回收 2)重用StringBuilder对象,使用delete(start,end) 3)重用StringBuilder对象,使用setLength(newLength)
将三种方法循环1000万次,代码:
public class StringBuilderClear {
static String a;
static long time;
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
time = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
StringBuilder sb2 = new StringBuilder();
sb2.append("someStr6ing");
sb2.append("someS5tring2");
sb2.append("some3Strin4g");
sb2.append("so3meStr5ing");
sb2.append("so2meSt7ring");
}
System.out.println("new StringBuilder方式:" + (System.currentTimeMillis() - time)+"ms ");
time = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
sb.append("someString");
sb.append("someString2");
sb.append("someStrin4g");
sb.append("someStr5ing");
sb.append("someSt7ring");
sb.delete(0, sb.length());
}
System.out.println("StringBuilder。delete()方式:" + (System.currentTimeMillis() - time)+"ms -> "+sb.capacity());
time = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
sb3.append("someStr55ing");
sb3.append("some44String2");
sb3.append("som55eStrin4g");
sb3.append("some66Str5ing");
sb3.append("so33meSt7ring");
sb3.setLength(0);
}
System.out.println("StringBuilder.setLength方式" + (System.currentTimeMillis() - time)+"ms -> "+sb3.capacity());
}
}
注意append的字符串要都不相同,否则会因为java 的String pool对结果造成影响(即3好于2)
结果:
new StringBuilder方式:861
StringBuilder.delete()方式:305 ms -> 70
StringBuilder.setLength方式337 ms -> 70
可以将各方法多重复几次,颠倒顺序,等 总体来看:方法2略好于方法3好于方法1
delete方法和setLength方法都是将count置为0;setLength方法只是多了一次ensureCapacityInternal(newLength)的函数调用
public AbstractStringBuilder delete(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
end = count;
if (start > end)
throw new StringIndexOutOfBoundsException();
int len = end - start;
if (len > 0) {
System.arraycopy(value, start+len, value, start, count-end);
count -= len;
}
return this;
}
其中
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
是一个本地方法。
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
ensureCapacityInternal(newLength){
// overflow-conscious code
if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity);
}
if (count < newLength) {
Arrays.fill(value, count, newLength, '