黑马程序员技术交流社区
标题:
对于字符串频繁操作
[打印本页]
作者:
_Water
时间:
2014-4-13 20:48
标题:
对于字符串频繁操作
本帖最后由 _Water 于 2014-4-13 20:50 编辑
字符串频繁操作下:StringBuffer、StringBuilder效率都要比用String高的多,测试代码:
The 0 [ String:1096 StringBuffer:1 StringBuilder:1 ]
The 1 [ String:1093 StringBuffer:0 StringBuilder:1 ]
The 2 [ String:1058 StringBuffer:0 StringBuilder:0 ]
The 3 [ String:1063 StringBuffer:0 StringBuilder:0 ]
The 4 [ String:1058 StringBuffer:0 StringBuilder:1 ]
The 5 [ String:1037 StringBuffer:1 StringBuilder:0 ]
The 6 [ String:1048 StringBuffer:0 StringBuilder:1 ]
The 7 [ String:1033 StringBuffer:0 StringBuilder:0 ]
The 8 [ String:1041 StringBuffer:1 StringBuilder:0 ]
The 9 [ String:1049 StringBuffer:0 StringBuilder:0 ]
class Test
{
private final int LOOP_TIMES=5000;
private final String CONSTANT_STRING ="abcdefghijklmnopqrstuvwxyz";
public static void main(String[] args)
{
new Test().startup();
}
public static void sop(String str)
{
System.out.print(str);
}
public void StrTest()
{
String str="";
long lstart1=System.currentTimeMillis();
for (int x =0;x<LOOP_TIMES ;x++ )
{
str+=CONSTANT_STRING;
}
long lend1=System.currentTimeMillis();
long span1=lend1-lstart1;
sop("String:"+span1);
}
public void StrBufferTest( )
{
StringBuffer sb =new StringBuffer();
long lstart2=System.currentTimeMillis();
for (int i =0;i<LOOP_TIMES ;i++ )
{
sb.append(CONSTANT_STRING);
}
long lend2=System.currentTimeMillis();
long span2=lend2-lstart2;
sop("StringBuffer:"+span2);
}
public void StrBuilderTest()
{
long lstart3=System.currentTimeMillis();
StringBuilder builder=new StringBuilder();
for (int i =0;i<LOOP_TIMES ;i++ )
{
builder.append(CONSTANT_STRING);
}
long lend3=System.currentTimeMillis();
sop("StringBuilder:"+(lend3-lstart3));
}
public void startup()
{
for (int i =0;i<10 ;i++ )
{
sop("The "+i+" [\t ");
StrTest();
sop("\t");
StrBufferTest();
sop("\t");
StrBuilderTest();
sop("\t");
sop("]");
System.out.println();
}
}
}
复制代码
作者:
Kelvinhu
时间:
2014-4-13 21:20
StringBuilder的前身是StringBuffer····················
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2