Identity HashMap 是 Java 中的一种特殊实现,它比较对象的引用而不是使用 equals()
方法,并且使用 identityHashCode()
而不是 hashCode()
。此外,它使用线性探测哈希表而不是条目列表。
Map<String, String> map = new HashMap<>();
Map<String, String> iMap = new IdentityHashMap<>();
这是否意味着如果正确调整,IdentifyHashMap
对于字符串键通常会更快?
看下面这个例子:
public class Dictionary {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("/usr/share/dict/words"));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
System.out.println("list.size() = " + list.size());
Map<String, Integer> iMap = new IdentityHashMap<>(list.size());
Map<String, Integer> hashMap = new HashMap<>(list.size());
long iMapTime = 0, hashMapTime = 0;
long time;
for (int i = 0; i < list.size(); i++) {
time = System.currentTimeMillis();
iMap.put(list.get(i), i);
time = System.currentTimeMillis() - time;
iMapTime += time;
time = System.currentTimeMillis();
hashMap.put(list.get(i), i);
time = System.currentTimeMillis() - time;
hashMapTime += time;
}
System.out.println("iMapTime = " + iMapTime + " hashMapTime = " + hashMapTime);
}
}
进行了非常基本的性能检查。我正在读取字典单词(235K)并将其推入两个映射表中。它会打印:
list.size() = 235886
iMapTime = 101 hashMapTime = 617
我认为这是一个很好的改进,除非我在这里做错了什么。
String == String
的检查与String.equal(String)
方法完全相同,所以我认为在这种情况下没有关系。那么,linear-probe hash table
是否会比常规 entry Set 提供改进呢?我只是好奇,所以没有确切的计数,但我们可以考虑可能有 5K+ 个字符串吗? - Himanshu AhireIdentityHashMap
大约快了20%。然而,我完全同意程序员的观点。你几乎肯定不应该使用IdentityHashMap
。 - Paul Boddington