StringBuffer 清空
阿新 • • 發佈:2018-07-13
review delete tle cin delet edit key nts code
幾種方法:
-
方法1:
1 2 3 4 StringBuffer 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:
1 my_StringBuffer.setLength(
0
);
//設置StringBuffer變量的長度為0
-
方法3:也是我以前一直用的
1 my_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對象中的內容效率最高
StringBuffer 清空