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

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

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

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

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

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

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

大师兄

使用的测试代码:

    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还快的呢?


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Java 代码优化:为什么有人说 StringTokenizer 会比String.split() 的效率高呢他测试了吗