StringBuffer清空操作效率分析

本文分析了StringBuffer在JDK中没有直接的clear操作,但可以通过setLength(0)或delete(0, length)来实现清空。通过源码解析和性能测试,发现setLength方法由于不涉及数组拷贝,其性能优于delete方法,是更优的清空StringBuffer的选择。" 79755545,7542339,MySQL与Oracle获取Top N记录的区别,"['数据库理论', 'SQL查询', 'MySQL', 'Oracle']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)方法效率较高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值