———Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ———
- String:定长的字符串,它的内容是不可以改变的,正因为如此,编译器可以让字符串共享.
- StringBuffer:可变长的字符串缓冲区,多线程操作是安全的,并且在字符串连接操作上提供了性能和效率都优于String类的"+"的append()方法,因此如果需要大量的频繁的进行字符连接操作时,优先采用StringBuffer的append()方法.如果只是简单的字符串连接可以采用String的"+"来提高代码的可读性.
- StringBuilder:是StringBuilder的一个等价类,区别在于StringBuilder是非线程安全的,但正因为如此少了很多同步的操作,在效率上要高于StringBuilder,因此如果不涉及多线程操作,可以优先考虑StringBuilder来提高方法的执行效率.
Java代码
- public class StringTest {
-
-
-
-
-
- public static void main(String[] args) {
- String s = "test";
-
- String str = "";
- long str_start = System.currentTimeMillis();
- for (int i = 0; i < 100000; i++) {
- str += s;
- }
- long str_end = System.currentTimeMillis();
- System.out.println("String need time is : " + (str_end - str_start));
-
-
- StringBuffer s_buffer = new StringBuffer("");
- long buf_start = System.currentTimeMillis();
- for (int i = 0; i < 100000; i++) {
- s_buffer.append(s);
- }
- long buf_end = System.currentTimeMillis();
- System.out.println("StringBuffer need time is :"
- + (buf_end - buf_start));
-
-
- StringBuilder s_builder = new StringBuilder("");
- long bui_start = System.currentTimeMillis();
- for (int i = 0; i < 100000; 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 : 129765StringBuffer need time is :10StringBuilder need time is : 3
- String,StringBuffer和StringBuider虽都属于字符串类型,但是在使用的时候不能混用,需要根据实际情况选择合适的字符串类型.有关它们更详细的介绍,请参考文档.
示例代码:Java代码
- public class PlusTest {
-
- public static void main(String[] args) {
- String a = "a";
- String b = "b";
- String c = a + b;
- String d = c + 1;
- }
- }
将上述代码编译后再反编译,得到的代码:
Java代码
- 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对象,效率低是必然的.