总结
3种方法均无感清空,效率相同,setLength(0)依然是最优解。(内存消耗最低)
结论表
1.设置3个StringBuffer,50万个元素,每个元素为随机UUID,以下是测试结果,
- 通常:3个方法无差别
- 执行万级别:没有绝对快慢
方法 | 描述 | 执行1-1000次 | 1万次 | 50万次 | 5000万次 |
setLength(0) | 设置StringBuffer 为0 | 0ms | 1ms | 16ms | 535ms |
delete(int start, int end) | 清空索引 start到end数据 | 0ms | 1ms | 14ms | 602ms |
new StringBuffer | 新建StringBuffer | 0ms | 0ms | 26ms | 2246ms |
执行结果
执行各方法次数为:1
StringBuffer-setLength:0
StringBuffer--delete:0
StringBuffer--new StringBuffer:0
执行各方法次数为:1000
StringBuffer-setLength:0
StringBuffer--delete:0
StringBuffer--new StringBuffer:0
执行各方法次数为:500000
StringBuffer-setLength:16
StringBuffer--delete:14
StringBuffer--new StringBuffer:26
执行各方法次数为:50000000
StringBuffer-setLength:535
StringBuffer--delete:602
StringBuffer--new StringBuffer:2246
测试代码
private static void testStringBufferclear(int times) {
StringBuffer sbf = new StringBuffer();
StringBuffer sbi = new StringBuffer();
StringBuffer sbj = new StringBuffer();
for (int i = 0; i < 500000; i++) {
sbf.append(UUID.randomUUID());
sbi.append(UUID.randomUUID());
sbj.append(UUID.randomUUID());
}
System.out.println("执行各方法次数为:"+times);
long s1 = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
sbi.setLength(0);
}
long s11 = System.currentTimeMillis();
System.out.println("StringBuffer-setLength:" + (s11 - s1));
s1 = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
sbf.delete(0, sbf.length());
}
s11 = System.currentTimeMillis();
System.out.println("StringBuffer--delete:" + (s11 - s1));
s1 = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
sbf = new StringBuffer("");
}
s11 = System.currentTimeMillis();
System.out.println("StringBuffer--new StringBuffer:" + (s11 - s1));
}
public static void main(String args[]) {
testStringBufferclear(1);
testStringBufferclear(1000);
testStringBufferclear(500000);
testStringBufferclear(50000000);
}