使用StringBuffer和StringBuilder代替String的+运算

使用StringBuffer和StringBuilder代替String的+运算

 

 

以下例子可以说明代替的理由

		long curTime = System.currentTimeMillis();
		String abc = "";
		for (int i = 0; i < 10000; i ++){
			abc += i + ",";
		}
		System.out.println("Normal : " + (System.currentTimeMillis() - curTime));
		
		curTime = System.currentTimeMillis();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < 10000; i ++){
			buffer.append(i).append(",");
		}
		abc = buffer.toString();
		System.out.println("StringBuffer : " + (System.currentTimeMillis() - curTime));
		
		curTime = System.currentTimeMillis();
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < 10000; i ++){
			builder.append(i).append(",");
		}
		abc = builder.toString();
		System.out.println("StringBuilder : " + (System.currentTimeMillis() - curTime));

 

----输出

Normal : 610
StringBuffer : 0
StringBuilder : 0

 

经过多次运算StringBuilder和StringBuffer都在15以下

你可能感兴趣的:(StringBuilder)