字符串有三种拼接方式:+号、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
网友评论