`

Java字符串拼接效率分析

阅读更多

关于字符串处理在Java中通常有三个类进行处理:

String
StringBuilder
StringBuffer

这三个类进行字符串拼接,StringBuilder和StringBuffer都有同样的方式,都拥有append()方法.而StringBuilder和StringBuffer不同之处在于,在做一次append操作的时候,StringBuffer是线程安全的(仅仅是在一次操作)。StringBuffer的线程安全在于,做append()操作的时候,在方法前增加了synchronized操作。所以可以预见StringBuilder和StringBuffer在做append()的方法的时候StringBuilder更快(而在单线程下,这种差异不是特别大)。

 

String类进行字符串添加的方式有两种:

1.直接使用 “+” 进行拼接

2.使用concat进行拼接

 

下面就根据这四种操作进行测试。

测试用例:

 

    private static final int OUTER_ITERATION = 20;
    private static final int INNER_ITERATION = 50000;

    @Test
    public void testString() {
        String addTestStr = "";

        for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) {

            StopWatch stopWatch = new LoggingStopWatch("StringAddConcat");

            addTestStr = "";

            for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++)

                addTestStr += "*";

            stopWatch.stop();
        }
        System.out.println(addTestStr);
    }
    @Test
    public void testStringConcat() {
        String concatTestStr = "";

        for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) {

            StopWatch stopWatch = new LoggingStopWatch("StringConcat");

            concatTestStr = "";

            for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++)

                concatTestStr = concatTestStr.concat("*");

            stopWatch.stop();

        }
    }
    @Test
    public void testStringBuffer() {
        StringBuffer concatTestSb = null;

        for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) {

            StopWatch stopWatch = new LoggingStopWatch("StringBufferConcat");

            concatTestSb = new StringBuffer();

            for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++)

                concatTestSb.append("*");

            stopWatch.stop();

        }
    }
    @Test
    public void testStringBuilder() {

        StringBuilder concatTestSbu = null;

        for (int outerIndex = 0; outerIndex <= OUTER_ITERATION; outerIndex++) {

            StopWatch stopWatch = new LoggingStopWatch("StringBuilderConcat");

            concatTestSbu = new StringBuilder();

            for (int innerIndex = 0; innerIndex <= INNER_ITERATION; innerIndex++)

                concatTestSbu.append("*");

            stopWatch.stop();

        }
    }

 

 

分别运行得到的结果

StringBuilder > StringBuffer > concat> +

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics