【发布时间】:2017-07-15 05:37:33
【问题描述】:
在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 中显示结果。 enter image description here
我正在使用 java6u45 java7u80 java8u131。
不明白为什么java8的性能会这么差
我正在尝试编写自己的 HashMap。
想学java8的HashMap哪个更好,但是没找到。
【问题讨论】:
-
因为返回单个静态值是一个可怕
hashCode()实现。不要那样做。执行return Integer.hashCode(i);,您应该会看到更好的 性能。 -
@ElliottFrisch 我正在测试哈希冲突。
-
HashMap的性能取决于您放入其中的键的hashCode()方法的实现程度。如果你有一个糟糕的hashCode()方法,不要指望它会表现良好。就像你有一个闪亮的新引擎,然后你往引擎里扔沙子并抱怨它的性能很差...... -
@Jesper 我只是比较java6 java7 java8 HashMap,而不是如何让HashMap更高效。我正在尝试编写自己的HashMap。我想在java8中学习HashMap,哪个更好,但是我没找到。
-
您的基准测试看起来不正确 - 使用 jmh。另请参阅stackoverflow.com/questions/504103/…