1. 程式人生 > >java中型別轉換那種效能最優

java中型別轉換那種效能最優

我們以String轉換為Integer為例,測試一下。

需要注意的是Ints.tryParse()方法用的google guava類庫;NumberUtils來自commons-lang類庫。

測試程式碼:

public class Test {

	public static int limit = 1000000;
	public static String sint = "9999";

	public static void main(String[] args) {
		
		long start = System.currentTimeMillis();
		for (int i = 0; i < limit; i++) {
			Integer integer = Integer.valueOf(sint);
		}
		long end = System.currentTimeMillis();

		System.out.println("valueOf took: " + (end - start));

		start = System.currentTimeMillis();
		for (int i = 0; i < limit; i++) {
			int integer = Integer.parseInt(sint);
		}
		end = System.currentTimeMillis();

		System.out.println("parseInt took: " + (end - start));

		start = System.currentTimeMillis();
		for (int i = 0; i < limit; i++) {
			int integer = Ints.tryParse(sint);
		}
		end = System.currentTimeMillis();

		System.out.println("Ints.tryParse took: " + (end - start));

		start = System.currentTimeMillis();
		for (int i = 0; i < limit; i++) {
			Integer integer = NumberUtils.createInteger(sint);
		}
		end = System.currentTimeMillis();

		System.out.println("numberUtils.createInteger took: " + (end - start));

		start = System.currentTimeMillis();
		for (int i = 0; i < limit; i++) {
			int integer = NumberUtils.toInt(sint);
		}
		end = System.currentTimeMillis();

		System.out.println("numberUtils.toInt took: " + (end - start));
	}

}

測試結果:
valueOf took: 31
parseInt took: 31
Ints.tryParse took: 78
numberUtils.createInteger took: 94
numberUtils.toInt took: 47