Java 字符串高效率拼接:+,contact,StringBuffer,StringBuilder 的性能比较,使用JProfiler测试

Java里面字符串拼接,估计是使用的最多的,经常使用的就是几种方式,谁的效率高呢:

1,直接使用“+”来拼接字符串

2,使用字符串自带的contact()方法

3,使用StringBuffer的append()和toString()方法

4,使用StringBuilder的append()和toString()方法

暂时就这么几个,若是再有的话,再继续比较。
 

下面看看,他们一起运行的时间占比截图

Java 字符串高效率拼接:+,contact,StringBuffer,StringBuilder 的性能比较,使用JProfiler测试_第1张图片

使用的测试代码:

     private static final String TTM = "0|probeName_lxk|188.188.8.118|10999|10.188.16.110|40998|grcb8583|{\"number\":\"78\",\"convers_id\": 12864829, \"msg_size\": 876, \"mti\": \"\", \"STAN\": \"  3133\", \"F38\": \"交易成功\", \"RC\": \"0000\", \"F41\": \"文件(PHPFG0),业务种类(000)\", \"mid\": \"\"}|||1|876|0|0|0|0|0|8|0|0|0|0|0|0|0|0|0|0|1536646259|1536646259923|2018-09-11T06:10:59|3166439542|180097134|6|0|7";
    public static void main(String[] args) {
        testStringContact();
    }
 
    private static void testStringContact() {
        String[] split = TTM.split("\\|");
        int length =split.length;
        while (true){
            String s = testAdd(split, length);
            String s1 = testStringBuilderAppend(split, length);
            String s2 = testStringBufferAppend(split, length);
            String s3 = testContact(split, length);
        }
    }
 
    private static String testContact(String[] split, int length) {
        String result = "";
        for (int i = 0; i < length; i++) {
            result = result.concat(split[i]);
        }
        return result;
    }
 
    private static String testStringBufferAppend(String[] split, int length) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            stringBuffer.append(split[i]);
        }
        return stringBuffer.toString();
    }
 
    private static String testStringBuilderAppend(String[] split, int length) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            stringBuilder.append(split[i]);
        }
        return stringBuilder.toString();
    }
 
    private static String testAdd(String[] split, int length) {
        String result = null;
        for (int i = 0; i < length; i++) {
            result +=split[i];
        }
        return result;
    }

有么有比这个builder还快的呢?
--------------------- 
作者:李学凯 
来源:CSDN 
原文:https://blog.csdn.net/qq_27093465/article/details/92430589 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(Java 字符串高效率拼接:+,contact,StringBuffer,StringBuilder 的性能比较,使用JProfiler测试)