62,621
社区成员
发帖
与我相关
我的任务
分享public class Test {
public static void main(String[] args) {
final int SIZE = 10000;
long start = 0;
String str = new String();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++)
str += "aba"+i;
System.out.println(System.currentTimeMillis() - start);
String str2 = new String();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
str2.concat("abc"+i);
System.out.println(System.currentTimeMillis() - start);
StringBuffer sb = new StringBuffer();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sb.append("abd"+i);
System.out.println(System.currentTimeMillis() - start);
StringBuilder sbu = new StringBuilder();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sbu.append("abe"+i);
System.out.println(System.currentTimeMillis() - start);
}
}
StringBuffer sb2 = new StringBuffer(3000000);
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sb2.append("abd");
System.out.println(System.currentTimeMillis() - start);
StringBuilder sbu2 = new StringBuilder(3000000);
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sbu2.append("abe");
System.out.println(System.currentTimeMillis() - start);
这样就好多了
String str2 = new String();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
str2.concat("abc");
System.out.println(System.currentTimeMillis() - start);
StringBuffer sb = new StringBuffer();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sb.append("abd");
System.out.println(System.currentTimeMillis() - start);
改成这样,为什么concat用的时间还是少些 public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}