Created
January 8, 2010 03:28
-
-
Save stepancheg/271825 to your computer and use it in GitHub Desktop.
HashMap vs. IdentityHashMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Main { | |
private static final Random random = new Random(); | |
static class A { | |
} /// end of A | |
static class B { | |
private final int hashCode = random.nextInt(); | |
@Override | |
public int hashCode() { | |
return hashCode; | |
} | |
} /// end of B | |
static final int keyCount = 100000; | |
static final int iterations = 200; | |
static void testIdentityHashCode() { | |
List<A> keys = new ArrayList<A>(); | |
Map<A, Integer> map = new IdentityHashMap<A, Integer>(); | |
for (int i = 0; i < keyCount; ++i) { | |
A key = new A(); | |
keys.add(key); | |
map.put(key, i); | |
} | |
int sum = 0; | |
for (int j = 0; j < iterations; ++j) { | |
for (A key : keys) { | |
sum += map.get(key); | |
} | |
} | |
System.err.println(sum); | |
} | |
static void testHashCode() { | |
List<B> keys = new ArrayList<B>(); | |
Map<B, Integer> map = new HashMap<B, Integer>(); | |
for (int i = 0; i < keyCount; ++i) { | |
B key = new B(); | |
keys.add(key); | |
map.put(key, i); | |
} | |
int sum = 0; | |
for (int j = 0; j < iterations; ++j) { | |
for (B key : keys) { | |
sum += map.get(key); | |
} | |
} | |
System.err.println(sum); | |
} | |
public static void main(String[] args) throws Exception { | |
for (;;) { | |
{ | |
long a = System.currentTimeMillis(); | |
testHashCode(); | |
System.err.println("hash code: " + (System.currentTimeMillis() - a)); | |
} | |
{ | |
long a = System.currentTimeMillis(); | |
testIdentityHashCode(); | |
System.err.println("identity hash code: " + (System.currentTimeMillis() - a)); | |
} | |
{ | |
long a = System.currentTimeMillis(); | |
testHashCode(); | |
System.err.println("hash code: " + (System.currentTimeMillis() - a)); | |
} | |
{ | |
long a = System.currentTimeMillis(); | |
testIdentityHashCode(); | |
System.err.println("identity hash code: " + (System.currentTimeMillis() - a)); | |
} | |
} | |
} | |
} /// end of Main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment