场景:
问题:
我看到了一个性能问题,并且发现System.identityHashCode可能是我的问题。
问题:
以下是我的基准测试(全部在同一硬件上运行):
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
bechmark程序的来源是:
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;
}
}
}
答案 0 :(得分:1)
您看到这种差异可能是因为System.identityHashCode花了一些时间进行内部化和/或在您的方法中内联Object.hashCode。另外,实际上,您正在测量分配时间,因为您在循环的每一步都实例化了一个对象。
试试这个:
public class HCTests {
static int ITS = 1000;
@Test
public void run() {
Object[] o = newArray(1000);
for (int i = 0; i < 10; i++) {
timeHash(o);
}
System.out.println("----------------");
for (int i = 0; i < 10; i++) {
timeHash(newArray(1000));
}
}
private Object[] newArray(int max) {
Object[] o = new Object[max];
for (int i = 0; i < o.length; i++) {
o[i] = new Object();
}
return o;
}
private void timeHash(Object[] o) {
//store the hashes to avoid possible dead-code elimination
int[] hashes=new int[o.length];
long start = System.nanoTime();
for (int j = 0; j < ITS; j++) {
for (int i = 0; i < o.length; i++) {
hashes[i]=System.identityHashCode(o);
}
}
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed " + elapsed + "(ns). Avg: " + (float)elapsed
/ (o.length * ITS));
for (int i : hashes) {
if(i==0) {
System.out.println("Ooops, got 0 hashCode!!!");
}
}
}}
对于我得到的第一个循环的输出(Old Intel Core 2 Duo 2.1GHz)
经历了7557271(ns)。平均值:7.557271
经历了18508470(ns)。平均值:18.50847
...
经历了2026678(ns)。平均值:2.026678
在第二个循环中我得到了
经历了2142041(ns)。平均值:2.142041
经历了1951888(ns)。平均值:1.951888
经历了1929891(ns)。平均值:1.929891
经历了1934779(ns)。平均:1.934779
经历了1993438(ns)。平均值:1.993438
经历了2133732(ns)。平均值:2.133732
经历了1995882(ns)。平均值:1.995882
经历了2326329(ns)。平均值:2.326329
经历了1939178(ns)。平均值:1.939178
经历了2275980(ns)。平均值:2.275981