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



你可能感兴趣的:(java,java,转换)