月度存档: 五月 2014

今天想测试map的读取key的性能,结果遇到无法解答的问题。

代码如下:

如果注释掉test2(),启动test2_1(),则test()消耗的时间大幅减少,不知原因。

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class Test4 {
	private static Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
	private static Map<String, String> map2 = new HashMap<String, String>();
	private static Map<String, String> map3 = new IdentityHashMap<String, String>();
	private static String testKey = "helloworld";
	private static long time;
	private static long time2;
	private static Integer a = 1500;

	public static void main(String[] args) {
		map3.put(testKey, testKey);
		for (int m = 1000; m < 1010; m++) {
			map1.put(m, m);
			map2.put("" + m, "" + m);
			map3.put("" + m, "" + m);
		}
		for (int mm = 0; mm < 100; mm++) {
			test1();
			test2();
			// test2_1();
		}
	}

	public static void test1() {
		time = System.nanoTime();
		for (int m = 0; m < 1000000000; m++) {
			map1.get(a);
		}
		time2 = System.nanoTime();
		System.out.println("数字:" + (time2 - time));
	}

	public static void test2() {
		time = System.nanoTime();
		for (int m = 0; m < 1000000000; m++) {
			map2.get("hello");
		}
		time2 = System.nanoTime();
		System.out.println("字符:" + (time2 - time));
	}

	public static void test2_1() {
		time = System.nanoTime();
		for (int m = 0; m < 1000000000; m++) {
			map2.get("hello222222222222222222222222222222222222222222222222222222222222222222222222222222222222222");
		}
		time2 = System.nanoTime();
		System.out.println("字符:" + (time2 - time));
	}

	public static void test3() {
		time = System.nanoTime();
		for (int m = 0; m < 1000000000; m++) {
			map3.get(testKey);
		}
		time2 = System.nanoTime();
		System.out.println("字符3:" + (time2 - time));
	}
}