HashMap遍历效率测试

测试环境:

win8.1 64bit 

CPU:Intel 奔腾3560M 2.4GHz

内存:8G 1600MHz

硬盘:三星SSD 256G


1.遍历测试,分别用keySet和entrySet做测试,测试代码如下:

@Test
	public void test() {
		int i, N = 2000001, testTimes = 100;
		long start, end, total_keySet, total_entrySet;
		double avg_keySet = 0, avg_entrySet = 0;
		HashMap hashMap = new HashMap();
		for (i = 0; i < N; i++) {
			hashMap.put(i, i + "");
		}
		for (i = 0; i < testTimes; i++) {

			//=========keySet==========
			start = System.nanoTime();

			Iterator it_ks = hashMap.keySet().iterator();

			while (it_ks.hasNext()) {
				int key = it_ks.next();
				String value = hashMap.get(key);
				//			System.out.println(key + "-" + value);
			}

			end = System.nanoTime();
			total_keySet = end - start;
			//=========keySet==========

			//*********entrySet*****************
			start = System.nanoTime();

			Iterator> it_et = hashMap.entrySet()
					.iterator();

			while (it_et.hasNext()) {
				Entry entry = it_et.next();
				//			System.out.println(entry.getKey() + "-" + entry.getValue());
			}
			end = System.nanoTime();
			total_entrySet = end - start;
			//*********entrySet*****************

			avg_keySet += total_keySet;
			avg_entrySet += total_entrySet;

		}
		System.out.println("The average time of keySet:     "
				+ BigDecimal.valueOf((long) (avg_keySet / 100.0), 9));
		System.out.println("The average time of entrySet:   "
				+ BigDecimal.valueOf((long) (avg_entrySet / 100.0), 9));
	}


100组测试结果平均耗时: 
  

The average time of keySet:     0.054277459The average time of entrySet:   0.020779901

HashMap中keySet和entrySet的部分源码:

 public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }

  public Set keySet() {
        Set ks = keySet;
        return (ks != null ? ks : (keySet = new KeySet()));
    }
public Set> entrySet() {
        return entrySet0();
    }

    private Set> entrySet0() {
        Set> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet());
    }
根据源码的意思,利用keySet获取K,V需要经过2个步骤(获取K,再获取V),而entrySet只需一个步骤.


结论:迭代遍历取HashMap值时,使用entrSet比keySet快.

你可能感兴趣的:(--1.1.Data,Structure)