---
title: "hashMap优化"
author: "linsky328"
date: "2017-06-30T15:51:42Z"
tags: []
categories: ["编程语言"]
slug: "hashmap"
draft: false
lastmod: "2017-06-30T17:16:23Z"
id: 2382280
url: "https://linsky328.iteye.com/blog/2382280"
---

1 集合初始化时，指定集合初始值大小。

   说明：HashMap 使用 HashMap(int initialCapacity) 初始化，

  正例：initialCapacity = (需要存储的元素个数 / 负载因子) + 1。注意负载因子（即 loader factor）默认为

  0.75，如果暂时无法确定初始值大小，请设置为 16。 反例：HashMap 需要放置 1024 个元素，由于没有  设置容量初始大小，随着元素不断增加，容

  量 7 次被迫扩大，resize 需要重建 hash 表，严重影响性能。

 

```
/**
	 * ArrayList大容量性能测试
	 */
	private static void performance() {
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		long a1 = System.currentTimeMillis();
		for (int i = 0; i < SIZE; i++) {
			map.put(i, i);
		}
		long a2 = System.currentTimeMillis();
		System.out.println("costs:" + (a2 - a1) + "ms");

		// 预先设置大小
		Map<Integer, Integer> map2 = new HashMap<Integer, Integer>(SIZE);
		for (int i = 0; i < SIZE; i++) {
			map2.put(i, i);
		}
		System.out.println("costs:" + (System.currentTimeMillis() - a2) + "ms");
	}
结果：
costs:692ms
costs:364ms
```

 

2 遍历：使用增强for循环  
      使用 entrySet 遍历 Map 类集合 KV，而不是 keySet 方式进行遍历。 说明：keySet 其实是遍历了 2 次，一次是转为 Iterator 对象，另一次是从 hashMap 中取出 key 所对应的 value。而 entrySet 只是遍历了一次就把 key 和 value 都放到了 entry 中，效 率更高。

写道

/\**  
\* map循环测试  
\*/  
private static void forEach() {  
Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;(SIZE);  
for (int i = 0; i &lt; SIZE; i++) {  
map.put(i, i);  
}  
long time1 = System.currentTimeMillis();  
Set&lt;Entry&lt;Integer, Integer&gt;&gt; set = map.entrySet();  
for (Entry&lt;Integer, Integer&gt; entry : set) {  
int code = entry.getKey().hashCode() + entry.getValue().hashCode();  
}  
long time2 = System.currentTimeMillis();  
System.out.println("costs1:" + (time2 - time1) + "ms");

for (Integer key : map.keySet()) {  
int code = key.hashCode() + map.get(key).hashCode();  
}  
long time3 = System.currentTimeMillis();  
System.out.println("costs2:" + (time3 - time2) + "ms");

map.forEach((key, value) -&gt; {  
int code = key.hashCode() + value.hashCode();  
});  
long time4 = System.currentTimeMillis();  
System.out.println("costs3:" + (time4 - time3) + "ms");  
}

结果：  
costs1:48ms  
costs2:59ms  
costs3:56ms