Java字符串连接

参考: http://www.blogjava.net/nokiaguy/archive/2008/05/07/198990.html

先看下面的代码:

package string;
  
  public class TestSimplePlus
  {
      public static void main(String[] args)
      {
          String s = "abc";
          String ss = "ok" + s + "xyz" + 5;
          System.out.println(ss);
      }
  }

编译后再进行反编译后结果如下:

package string;

import java.io.PrintStream;

public class TestSimplePlus
{
    public TestSimplePlus()
    {
    //    0    0:aload_0         
    //    1    1:invokespecial   #8   
    //    2    4:return          
    }

    public static void main(String args[])
    {
      String s = "abc";
    //    0    0:ldc1            #16  
    //    1    2:astore_1        
      String ss = (new StringBuilder("ok")).append(s).append("xyz").append(5).toString();
    //    2    3:new             #18  
    //    3    6:dup             
    //    4    7:ldc1            #20  
    //    5    9:invokespecial   #22  
    //    6   12:aload_1         
    //    7   13:invokevirtual   #25  
    //    8   16:ldc1            #29  
    //    9   18:invokevirtual   #25  
    //   10   21:iconst_5        
    //   11   22:invokevirtual   #31  
    //   12   25:invokevirtual   #34  
    //   13   28:astore_2        
      System.out.println(ss);
    //   14   29:getstatic       #38  
    //   15   32:aload_2         
    //   16   33:invokevirtual   #44  
    //   17   36:return          
    }
}

使用jad反编译的好处之一就是可以同时生成字节码和源代码。这样可以进行对照研究。从上面的代码很容易看出,虽然在源程序中使用了"+",但在编译时仍然将"+"转换成StringBuilder。因此,我们可以得出结论,在Java中无论使用何种方式进行字符串连接,实际上都使用的是StringBuilder。这里如果将变量S去掉,变成String ss = "ok" + "xyz" + 5; 这样在反编译后这里并没有产生StringBulider对象,因为JVM编译器对于"ok" + s + "xyz" + 5;的处理方式和对于"ok" + "xyz" + 5;不一样,后者在编译期的值就可以确定下来,因为都是字符串常量。故在程序运行期不会产生StringBulider对象,而前者不同,s的值在编译期无法确定,所以JVM就会在运行期产生StringBulider对象来进行append。

那么是不是可以根据这个结论推出使用"+"和StringBuilder的效果是一样的呢?这个要从两个方面的解释。如果从运行结果来解释,那么"+"和StringBuilder是完全等效的。但如果从运行效率和资源消耗方面看,那它们将存在很大的区别。

当然,如果连接字符串行表达式很简单(如上面的顺序结构),那么"+"和StringBuilder基本是一样的,但如果结构比较复杂,如使用循环来连接字符串,那么产生的Java Byte Code就会有很大的区别。先让我们看看如下的代码:

package string;
  
  import java.util.*;
  
  public class TestComplexPlus
  {
      public static void main(String[] args)
      {
          String s = "";
          Random rand = new Random();
          for (int i = 0; i < 10; i++)
          {
              s = s + rand.nextInt(1000) + " ";
          }
          System.out.println(s);
      }
  }

上面的代码返编译后的Java Byte Code如下:

package string;

import java.io.PrintStream;
import java.util.Random;

public class TestComplexPlus
{

    public TestComplexPlus()
    {
    //    0    0:aload_0         
    //    1    1:invokespecial   #8   
    //    2    4:return          
    }

    public static void main(String args[])
    {
        String s = "";
    //    0    0:ldc1            #16  
    //    1    2:astore_1        
        Random rand = new Random();
    //    2    3:new             #18  
    //    3    6:dup             
    //    4    7:invokespecial   #20  
    //    5   10:astore_2        
        for(int i = 0; i < 10; i++)
    //*   6   11:iconst_0        
    //*   7   12:istore_3        
    //*   8   13:goto            49
         s = (new StringBuilder(String.valueOf(s))).append(rand.nextInt(1000)).append(" ").toString();
    //    9   16:new             #21  
    //   10   19:dup             
    //   11   20:aload_1         
    //   12   21:invokestatic    #23  
    //   13   24:invokespecial   #29  
    //   14   27:aload_2         
    //   15   28:sipush          1000
    //   16   31:invokevirtual   #32  
    //   17   34:invokevirtual   #36  
    //   18   37:ldc1            #40  
    //   19   39:invokevirtual   #42  
    //   20   42:invokevirtual   #45  
    //   21   45:astore_1        

    //   22   46:iinc            3  1
    //   23   49:iload_3         
    //   24   50:bipush          10
    //   25   52:icmplt          16
        System.out.println(s);
    //   26   55:getstatic       #49  
    //   27   58:aload_1         
    //   28   59:invokevirtual   #55  
    //   29   62:return          
    }
}

大家可以看到,虽然编译器将"+"转换成了StringBuilder,但创建StringBuilder对象的位置却在for语句内部。这就意味着每执行一次循环,就会创建一个StringBuilder对象(对于本例来说,是创建了10个StringBuilder对象),虽然Java有垃圾回收器,但这个回收器的工作时间是不定的。如果不断产生这样的垃圾,那么仍然会占用大量的资源。解决这个问题的方法就是在程序中直接使用StringBuilder来连接字符串,代码如下:

package string;

import java.util.*;

public class TestStringBuilder
{
    public static void main(String[] args)
    {
        String s = "";
        Random rand = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 10; i++)
        {
            result.append(rand.nextInt(1000));
            result.append(" ");
        }
        System.out.println(result.toString());
    }
}

上面代码反编译后的结果如下:

package string;

import java.io.PrintStream;
import java.util.Random;

public class TestStringBuilder
{

    public TestStringBuilder()
    {
    //    0    0:aload_0         
    //    1    1:invokespecial   #8   
    //    2    4:return          
    }

    public static void main(String args[])
    {
        String s = "";
    //    0    0:ldc1            #16  
    //    1    2:astore_1        
        Random rand = new Random();
    //    2    3:new             #18  
    //    3    6:dup             
    //    4    7:invokespecial   #20  
    //    5   10:astore_2        
        StringBuilder result = new StringBuilder();
    //    6   11:new             #21  
    //    7   14:dup             
    //    8   15:invokespecial   #23  
    //    9   18:astore_3        
        for(int i = 0; i < 10; i++)
    //*  10   19:iconst_0        
    //*  11   20:istore          4
    //*  12   22:goto            47
        {
            result.append(rand.nextInt(1000));
    //   13   25:aload_3         
    //   14   26:aload_2         
    //   15   27:sipush          1000
    //   16   30:invokevirtual   #24  
    //   17   33:invokevirtual   #28  
    //   18   36:pop             
            result.append(" ");
    //   19   37:aload_3         
    //   20   38:ldc1            #32  
    //   21   40:invokevirtual   #34  
    //   22   43:pop             
        }

    //   23   44:iinc            4  1
    //   24   47:iload           4
    //   25   49:bipush          10
    //   26   51:icmplt          25
        System.out.println(result.toString());
    //   27   54:getstatic       #37  
    //   28   57:aload_3         
    //   29   58:invokevirtual   #43  
    //   30   61:invokevirtual   #47  
    //   31   64:return          
    }
}

从上面的反编译结果可以看出,创建StringBuilder的代码被放在了for语句外。虽然这样处理在源程序中看起来复杂,但却换来了更高的效率,同时消耗的资源也更少了。

在使用StringBuilder时要注意,尽量不要"+"和StringBuilder混着用,否则会创建更多的StringBuilder对象。

你可能感兴趣的:(Java字符串连接)