在学习Java8中HashMap的源代码过程中,我有一个问题。
源代码非常复杂,效率有多高?
因此,我编写了一个关于哈希冲突的代码。
public class Test {
final int i;
public Test(int i) {
this.i = i;
}
public static void main(String[] args) {
java.util.HashMap<Test, Test> set = new java.util.HashMap<Test, Test>();
long time;
Test last;
Random random = new Random(0);
int i = 0;
for (int max = 1; max < 200000; max <<= 1) {
long c1 = 0, c2 = 0;
int t = 0;
for (; i < max; i++, t++) {
last = new Test(random.nextInt());
time = System.nanoTime();
set.put(last, last);
c1 += (System.nanoTime() - time);
last = new Test(random.nextInt());
time = System.nanoTime();
set.get(last);
c2 += (System.nanoTime() - time);
}
System.out.format("%d\t%d\t%d\n", max, (c1 / t), (c2 / t));
}
}
public int hashCode() {
return 0;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Test))
return false;
Test t = (Test) obj;
return t.i == this.i;
}
}
我在Excel中展示结果。 点击此处查看图片描述
我正在使用java6u45,java7u80和java8u131。
我不明白为什么java8的性能会如此糟糕。
我试着写自己的HashMap。
我想学习java8中更好的HashMap,但是我没有找到它。
return Integer.hashCode(i);
,你应该会看到性能更好。 - Elliott FrischHashMap
的性能取决于你放入其中的键的hashCode()
方法实现得有多好。如果你有一个糟糕的hashCode()
方法,不要指望它能表现出色。这就像你有一台闪亮新引擎,然后你往里面扔沙子,然后抱怨它表现不佳... - Jesper