Collection和Map都有相应的clear操作,但是StringBuffer和StringBuilder没有,那么如何复用呢?
观察api我们知道有两种方式:
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,因此性能相对高点。