Collection和Map都有相应的clear操作,但是StringBuffer和StringBuilder没有,那么如何复用呢?
查看JDK文档,我们知道有两种方式:
StringBuffer sb=new StringBuffer();
sb.setLength(0);
sb.delete(0, sb.length());
我们观察下他们的区别:
他们的实现都是在AbstractStringBuilder里进行的,详情如下:
setLength:
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
if (newLength > value.length)
expandCapacity(newLength);
if (count < newLength) {
for (; count < newLength; count++)
value[count] = '\0';
} else {
count = newLength;
}
}
delete:
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;
}
我们发现setLength没有执行cp(数组拷贝)操作,只是重置count,因此性能相对高点。
测试程序如下
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
testStringBufferclear();
}
private static void testStringBufferclear() {
StringBuffer sbf = new StringBuffer("wwwwww");
StringBuffer sbi = new StringBuffer("wwwwww");
long s1 = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
sbi.setLength(0);
}
long s11 = System.currentTimeMillis();
System.out.println("StringBuffer-setLength:" + (s11 - s1));
s1 = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
sbf.delete(0, sbf.length());
}
s11 = System.currentTimeMillis();
System.out.println("StringBuffer--delete:" + (s11 - s1));
s1 = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
sbf = new StringBuffer("");
}
s11 = System.currentTimeMillis();
System.out.println("StringBuffer--new StringBuffer:" + (s11 - s1));
}
}
运行结果
StringBuffer-setLength:23
StringBuffer--delete:32
StringBuffer--new StringBuffer:91
从结果粗略可以看出,setLength()方法用时较短,因此在StringBuffer 清空操作中,使用setLength(int newLength)方法效率较高。