String 为固定长度的不可变的字符串
StringBuilder 为可变的,且提供个最好的性能,其代码如下
view plaincopy to clipboardprint?
public StringBuilder append(int i) {
super.append(i);
return this;
}
public StringBuilder append(int i) {
super.append(i);
return this;
}view plaincopy to clipboardprint?
StringBuffer 为可变的,且提供了同步安全的机制,代码如下<PRE class=java name="code"> public synchronized StringBuffer append(int i) {
super.append(i);
return this;
}</PRE>
<PRE class=java name="code"> </PRE>
<PRE class=java name="code">可以看到2个的区别就是StringBuffer是同步的 synchronized </PRE>
<PRE class=java name="code"> </PRE>
<PRE class=java name="code"><STRONG><FONT size=4>下面是3个性能测试代码</FONT></STRONG></PRE>
<PRE class=java name="code"><PRE class=java name="code">import java.util.Map;
public class MyTest {
/**
* @param args
*/
public static void main(String[] args) {
testString();
testStringBuilder();
testStringBufer();
}
static int NUMBER = 10000;
public static void testString() {
long begin = System.currentTimeMillis();
String str = "";
for (int i = 1; i < NUMBER; i++) {
str = str + i;
}
System.out.println("testString=" + (System.currentTimeMillis() - begin));
}
public static void testStringBuilder() {
long begin = System.currentTimeMillis();
StringBuilder b = new StringBuilder();
for (int i = 1; i < NUMBER; i++) {
b.append(i);
}
String str = b.toString();
System.out.println("testStringBuilder=" + (System.currentTimeMillis() - begin));
}
public static void testStringBufer() {
long begin = System.currentTimeMillis();
StringBuffer b = new StringBuffer();
for (int i = 1; i < NUMBER; i++) {
b.append(i);
}
String str = b.toString();
System.out.println("testStringBufer=" + (System.currentTimeMillis() - begin));
}
}</PRE>
<PRE class=java name="code"> </PRE>
<PRE class=java name="code"><STRONG>运行结果如下</STRONG></PRE>
<PRE class=java name="code">testString=750<BR>testStringBuilder=0<BR>testStringBufer=0<BR></PRE>
<PRE class=java name="code">可见String的操作是非常消耗资源的,而另外2个则性能优异。</PRE>
<PRE class=java name="code"> </PRE>
<PRE class=java name="code">对于StringBuilder和StringBuffer的对比,就没有必要了。他们的代码相同,只是缺少了同步而已。</PRE>
<PRE class=java name="code"> </PRE>
<PRE class=java name="code"><STRONG><FONT size=4>结论</FONT></STRONG></PRE>
<PRE class=java name="code">大多是情况下,StringBuilder是很好的选择</PRE>
</PRE>