StringBuilder和StringBuffer的效率比较
结论
- 在万级的使用里面,效率没有可比性,不需要太过关注
- 在十万即以后,效率渐渐显现,StringBuilder慢慢站住优势,效率倍数最高到了3倍
- 到亿级以后,差距不大,但还是StringBuilder要稍微快些
- 内存方面, 在百万级别以后StringBuilder内存使用明显低一些,到亿级以后差距不大
执行代码
public class Test {
public static Runtime runtime = Runtime.getRuntime();
public static void main(String[] args) {
long maxMemory = runtime.maxMemory();
System.out.println("最大内存: " + maxMemory/1024/1024 + "M");
int [] times = {10000, 100000, 1000000, 10000000, 100000000, 1000000000};
for (int i : times) {
System.out.println("循环执行次数:" + i);
StringBuilderTest(i);
StringBufferTest(i);
System.out.println();
}
}
private static void StringBuilderTest(int times){
StringBuilder sbd = new StringBuilder();
long start = System.currentTimeMillis();
while (sbd.length() < times) {
sbd.append("a");
}
System.out.println("StringBuilder执行时间:" + (System.currentTimeMillis() - start));
System.out.println("StringBuilder使用内存: " + (runtime.totalMemory() - runtime.freeMemory())/1024/1024 + "M");
}
private static void StringBufferTest(int times){
StringBuffer sbf = new StringBuffer();
long start = System.currentTimeMillis();
while (sbf.length() < times) {
sbf.append("a");
}
System.out.println("StringBuffer执行时间:" + (System.currentTimeMillis() - start));
System.out.println("StringBuffer使用内存: " + (runtime.totalMemory() - runtime.freeMemory())/1024/1024 + "M");
}
}
执行结果
最大内存: 7282M
循环执行次数:10000
StringBuilder执行时间:1
StringBuilder使用内存: 15M
StringBuffer执行时间:1
StringBuffer使用内存: 15M
循环执行次数:100000
StringBuilder执行时间:3
StringBuilder使用内存: 15M
StringBuffer执行时间:6
StringBuffer使用内存: 15M
循环执行次数:1000000
StringBuilder执行时间:11
StringBuilder使用内存: 17M
StringBuffer执行时间:24
StringBuffer使用内存: 21M
循环执行次数:10000000
StringBuilder执行时间:86
StringBuilder使用内存: 94M
StringBuffer执行时间:94
StringBuffer使用内存: 165M
循环执行次数:100000000
StringBuilder执行时间:720
StringBuilder使用内存: 545M
StringBuffer执行时间:731
StringBuffer使用内存: 856M
循环执行次数:1000000000
StringBuilder执行时间:6782
StringBuilder使用内存: 4546M
StringBuffer执行时间:7703
StringBuffer使用内存: 4583M