package javaBasic;import java.text.SimpleDateFormat;import java.util.Date;/** * JAVA的字符串拼接与性能 * * @author markGao * * 我们将执行20个拼接”*”50,000次的测试。下面是我们将使用到的拼接字符串的方法: */public class StringAndStrBuffAndStrBuilderCompare { private static final int OUTER_ITERATION = 20; private static final int INNER_ITERATION = 50000; String addTestStr = ""; String concatTestStr = ""; StringBuffer concatTestSb = null; StringBuilder concatTestSbu = null; SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS"); StringAndStrBuffAndStrBuilderCompare() { } public void test() { System.out.println("StringAddConcat " + sdFormat.format(new Date())); for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) { addTestStr = ""; for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++) addTestStr += "*"; } System.out.println("StringAddConcat " + sdFormat.format(new Date())); System.out.println("StringConcat " + sdFormat.format(new Date())); for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) { concatTestStr = ""; for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++) concatTestStr.concat("*"); } System.out.println("StringConcat " + sdFormat.format(new Date())); System.out.println("StringBufferConcat " + sdFormat.format(new Date())); for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) { concatTestSb = new StringBuffer(); for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++) concatTestSb.append("*"); } System.out.println("StringBufferConcat " + sdFormat.format(new Date())); System.out .println("StringBuilderConcat " + sdFormat.format(new Date())); for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) { concatTestSbu = new StringBuilder(); for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++) concatTestSbu.append("*"); } System.out .println("StringBuilderConcat " + sdFormat.format(new Date())); } /** * 这段代码是String.concat()的字节码,从这段代码中,我们可以清楚的看到,concat()方法使用了 * StringBuilder,concat()的性能应该和StringBuilder的一样好,但是由于额外的创建StringBuilder和 * 做.append(str).append(str).toString()的操作,使得concate的性能会受到一些影响,所以 * StringBuilder和String Cancate的时间是1.8和3.3。 * * 因此,即时在做最简单的拼接时,如果我们不想创建StringBuffer或StringBuilder实例使,我们也因该使用concat。 * 但是对于大量的字符串拼接操作,我们就不应该使用concat(译者注:因 * 为测试代码功能上并不完全等价,更换后的测试代码concat的平均处理时间是1650.9毫秒。这个结果在原文的评论里面。),因为concat会降低 * 你程序的性能,消耗你的cpu。因此,在不考虑线程安全和同步的情况下,为了获得最高的性能,我们应尽量使用StringBuilder * * @param args */ public static void main(String[] args) { StringAndStrBuffAndStrBuilderCompare test = new StringAndStrBuffAndStrBuilderCompare(); test.test(); }}