字符串连接:使用StringBuffer#append来替代”+”真的会带来性能提升吗?

We know:


1.StringBuffer sb = new StringBuffer(); //默认的缓冲区大小是16


2.用 + 来连接字符串,编译的时候,会自动转换成StringBuffer


for example:【参考于大神之作:http://www.ticmy.com/?p=69】

String s = "today is " + "a good day";

编译直接形成:

 Code:
0:   ldc     #5; //String today is a good day

  String tmp = " on the desk" ;
String s2 = "there are " + count + " books " + tmp;
编译直接形成:
   Code:
    0 :   iconst_2
    1 :   istore_0
    2 :   ldc     # 8 ; //String  on the desk
    4 :   astore_1
    5 :   new     # 9 ; //class java/lang/StringBuilder
    8 :   dup
    9 :   invokespecial   # 10 ; //Method java/lang/StringBuilder."":()V
    12 :  ldc     # 11 ; //String there are
    14 :  invokevirtual   # 12 ; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    17 :  iload_0
    18 :  invokevirtual   # 13 ; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
    21 :  ldc     # 14 ; //String  books
    23 :  invokevirtual   # 12 ; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    26 :  aload_1
    27 :  invokevirtual   # 12 ; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    30 :  invokevirtual   # 15 ; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    33 :  astore_2

但是对于循环内部(每次创建会引起性能损耗不少):
  String s3 = "" ;
         for ( int i= 0 ; i< 100 ; i++) {
             s3 = s3 + i;
         }
   Code:
    0 :   ldc     # 16 ; //String
    2 :   astore_0
    3 :   iconst_0
    4 :   istore_1
    5 :   iload_1
    6 :   bipush  100
    8 :   if_icmpge       36
    11 new     # 9 ; //class java/lang/StringBuilder
    14 :  dup
    15 :  invokespecial   # 10 ; //Method java/lang/StringBuilder."":()V
    18 :  aload_0
    19 :  invokevirtual   # 12 ; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    22 :  iload_1
    23 :  invokevirtual   # 13 ; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
    26 :  invokevirtual   # 15 ; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;




We get:


1.有的时候默认的缓冲区大小不够用,需要扩大,这就会影响到性能。如果我们在初始化的时候,设置一个合适的大小,new StringBuffer(xxx);这样就能在一定程度上提高性能。


2.在循环中使用 + 时,编译器的优化并不如我们期望的那么好,所以就要自己来吧new StringBuffer(xxx)拿出来,写外边了

String s3 = "" ;
StringBuilder tmp = new StringBuilder();
tmp.append(s3);
for ( int i= 0 ; i< 100 ; i++) {
     tmp.append(i);
}
s3 = tmp.toString();




你可能感兴趣的:(实践)