StringBuilder和StringBuffer的效率比较

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


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值