您的位置:首页 > Web前端

StringBuffer清空操作delete和setLength的效率对比分析

2017-08-21 13:18 471 查看
转载自:http://blog.csdn.net/ylyg050518/article/details/49430705

Collection和Map都有相应的clear操作,但是StringBuffer和StringBuilder没有,那么如何复用呢?

查看JDK文档,我
4000
们知道有两种方式:
StringBuffer sb=new StringBuffer();
sb.setLength(0);
sb.delete(0, sb.length());
1
2
3
1
2
3

我们观察下他们的区别:

他们的实现都是在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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3
4
5
6
7
8
9
10
11
12
13

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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1
2
3
4
5
6
7
8
9
10
11
12
13
14

我们发现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));
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

运行结果
StringBuffer-setLength:23
StringBuffer--delete:32
StringBuffer--new StringBuffer:91
1
2
3
1
2
3

从结果粗略可以看出,setLength()方法用时较短,因此在StringBuffer 清空操作中,使用setLength(int newLength)方法效率较高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: