String:定长的字符串,它的内容是不可以改变的,正因为如此,编译器可以让字符串共享.
StringBuffer:可变长的字符串缓冲区,多线程操作是安全的,并且在字符串连接操作上提供了性能和效率都优于String类的"+"的append()方法,因此如果需要大量的频繁的进行字符连接操作时,优先采用StringBuffer的append()方法.如果只是简单的字符串连接可以采用String的"+"来提高代码的可读性.
StringBuilder:是StringBuilder的一个等价类,区别在于StringBuilder是非线程安全的,但正因为如此少了很多同步的操作,在效率上要高于StringBuilder,因此如果不涉及多线程操作,可以优先考虑StringBuilder来提高方法的执行效率.
public class StringTest {
/**
* main method
*
* @param args
*/
public static void main(String[] args) {
String s = "test";
// String test
String str = "";
long str_start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
str += s;
}
long str_end = System.currentTimeMillis();
System.out.println("String need time is : " + (str_end - str_start));
// StringBuffer test
StringBuffer s_buffer = new StringBuffer("");
long buf_start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
s_buffer.append(s);
}
long buf_end = System.currentTimeMillis();
System.out.println("StringBuffer need time is :"
+ (buf_end - buf_start));
// StringBuilder testF
StringBuilder s_builder = new StringBuilder("");
long bui_start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
s_builder.append(s);
}
long bui_end = System.currentTimeMillis();
System.out.println("StringBuilder need time is : "
+ (bui_end - bui_start));
}
}
运行结果:
String need time is : 83485
StringBuffer need time is :15
StringBuilder need time is : 0
string中"+"实现字符串连接分析:
public class PlusTest {
public static void main(String[] args) {
String a = "a";
String b = "b";
String c = a + b;
String d = c + 1;
}
}
将该段代码编译与反编译(反编译参考):
public class PlusTest
{
public PlusTest()
{
}
public static void main(String args[])
{
String a = "a";
String b = "b";
String c = (new StringBuilder(String.valueOf(a))).append(b).toString();
String d = (new StringBuilder(String.valueOf(c))).append(1).toString();
}
}
通过反编译的结果可以看出,"+"实现字符串连接的过程中,实际上是借助了StringBuilder类的append方法,每拼接一次都要实例化一个StringBuilder对象,效率低是必然的.