Java字符串连接性能实测

在Java开发中,合并字符串通常使用两种方式:

  1. 使用String的+=操作符,这种情况适用于小规模的字符串连接。
  2. 使用StringBuffer的append方法,适用于大规模的场景。

参见如下示例:

import java.util.*;
import java.math.*;

public class TestStringBuffer {

	private static int LOOP_NUM = 10000;
	
	private static List stringList = new ArrayList();
	
	private static void generateList(){
		double randomNum;
		for (int i = 0; i < TestStringBuffer.LOOP_NUM; i++){
			randomNum = Math.random();
			stringList.add(Double.valueOf(randomNum).toString());
		}
	}
	
	public static void main(String[] args) {
		//Generate the String List
		long generateStartTime = System.currentTimeMillis();
		TestStringBuffer.generateList();
		long generateEndTime = System.currentTimeMillis();
		System.out.println("### The generation costs " + (generateEndTime - 
				generateStartTime) + " ms");

		//Use += to concat the String List
		long splusStart = System.currentTimeMillis();
		String concat = "";
		for (int i = 0 ; i < stringList.size(); i++){
			concat += stringList.get(i);
		}
		long splusEnd = System.currentTimeMillis();
		System.out.println("### The direct concat costs " + (splusEnd - 
				splusStart) + " ms");
		
		//Use StringBuffer to concat the String List
		long sbStart = System.currentTimeMillis();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < stringList.size(); i++){
			sb.append(stringList.get(i));
		}
		long sbEnd = System.currentTimeMillis();
		System.out.println("### The StringBuffer concat costs " + (sbEnd - 
				sbStart) + " ms");
	}
}

 

运行结果如下,可以看出性能相差近千倍。

### The generation costs 151 ms
### The direct concat costs 158427 ms
### The StringBuffer concat costs 40 ms

 

你可能感兴趣的:(java)