几种方法:
-
方法1:
1234StringBuffer my_StringBuffer =
new
StringBuffer();
my_StringBuffer.append(
'helloworld'
);
//添加字符串到StringBuffer中
int
sb_length = my_StringBuffer.length();
// 取得字符串的长度
my_StringBuffer.delete(
0
,sb_length);
//删除字符串从0~sb_length-1处的内容 (这个方法就是用来清除StringBuffer中的内容的)
-
方法2:
1my_StringBuffer.setLength(
0
);
//设置StringBuffer变量的长度为0
-
方法3:也是我以前一直用的
1my_StringBuffer =
new
StringBuffer()
几种方法的效率:
测试程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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
|
StringBuffer-setLength: 63 StringBuffer--delete: 109 StringBuffer-- new StringBuffer: 78 |
测试结论:
要通过使用sbi.setLength(0);来清空StringBuffer对象中的内容效率最高