现场:
- 我正在使用 XStream,它经常使用 System.identityHashCode。
- 我已从 IBM Java 1.5 迁移到 Oracle Java 7
问题:
我看到了一个性能问题,并且发现 System.identityHashCode 可能是我的问题。
问题:
- 有什么好的解释为什么我看到新 Java 的性能下降(以及从 IBM 到 Oracle 的变化)?
- 我如何绕过这个瓶颈?
以下是我的基准测试(都在相同的硬件上运行):
32 bit Oracle Java 7
System.identityHashCode: 517669471 - 51ns
Object.hashCode: 491220730 - 49ns
64 bit Oracle Java 7:
System.identityHashCode: 353134647 - 35ns
Object.hashCode: 339331774 - 33ns
IBM Java 1.5
System.identityHashCode: 19241979 - 1ns
Object.hashCode: 89621026 - 8ns
基准测试程序的来源是:
import java.util.*;
public class HashCodeTest
{
static int ITS = 10000000;
static Object O = new Object();
public static void main(String[] args)
{
TreeSet<Integer> large = new TreeSet<Integer>();
Random ran = new Random();
for (int i=0; i<10000; i++) {
large.add(ran.nextInt());
}
testIdentityHashCode(large);
testHashCode(large);
testIdentityHashCode(large);
testHashCode(large);
}
protected static void testIdentityHashCode(TreeSet<Integer> large)
{
long start = System.nanoTime();
for (int i=0; i<ITS; i++) {
Object o = new Container(large);
System.identityHashCode(o);
}
long end = System.nanoTime();
System.out.println("System.identityHashCode: " + (end-start) + " - " + (end-start)/ITS + "ns");
}
protected static void testHashCode(TreeSet<Integer> large)
{
long start = System.nanoTime();
for (int i=0; i<ITS; i++) {
Object o = new Container(large);
o.hashCode();
}
long end = System.nanoTime();
System.out.println("Object.hashCode: " + (end-start) + " - " + (end-start)/ITS + "ns");
}
private static class Container {
private final Object o;
public Container(Object o)
{
this.o = o;
}
}
}