美文网首页
字符串的拼接方法

字符串的拼接方法

作者: 以宇宙为海的蓝鲸 | 来源:发表于2019-07-26 21:35 被阅读0次

字符串有三种拼接方式:+号、string的concat()方法、StringBuffer的append()方法。

运行效率:append>concat>+。如果+号两边是字面值,则+号运行效率最高。

例:

public class Demo01 {
    public static void main(String[] args) {
        test01();
        test02();
        test03();
    }
    public static void test01() {
        long start = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer("a");
        for(int i = 0;i<100000;i++) {
            sb.append("b");
        }
        long end = System.currentTimeMillis();
        System.out.println("append的运行时间:"+(end-start));
    }
    public static void test02() {
        long start = System.currentTimeMillis();
        String s = new String("c");
        for(int i = 0;i<100000;i++) {
            s = s + "d";
        }
        long end = System.currentTimeMillis();
        System.out.println("+号的运行时间:"+(end-start));
    }
    public static void test03() {
        long start = System.currentTimeMillis();
        String s = new String("e");
        for(int i = 0;i<100000;i++) {
            s = s.concat("f");
        }
        long end = System.currentTimeMillis();
        System.out.println("concat的运行时间:"+(end-start));
    }
}

运行结果:

append的运行时间:5
+号的运行时间:3671
concat的运行时间:1725

相关文章

网友评论

      本文标题:字符串的拼接方法

      本文链接:https://www.haomeiwen.com/subject/kgdjrctx.html