Skip to content

Commit

Permalink
Containers in Depth: Exercise 35
Browse files Browse the repository at this point in the history
  • Loading branch information
kean0212 committed May 30, 2017
1 parent 13937a4 commit 6f58cd0
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
67 changes: 67 additions & 0 deletions ContainersInDepth/MapPerformance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.LinkedHashMap;
import java.util.IdentityHashMap;
import java.util.WeakHashMap;
import java.util.Hashtable;

public class MapPerformance {
static List<Test<Map<Integer, Integer>>> tests = new ArrayList<>();

static {
tests.add(new Test<Map<Integer, Integer>>("put") {
int test(Map<Integer, Integer> map, TestParam testParam) {
int loops = testParam.loops;
int size = testParam.size;
for (int i = 0; i < loops; ++i) {
map.clear();
for (int j = 0; j < size; ++j) {
map.put(j, j);
}
}
return loops * size;
}
});
tests.add(new Test<Map<Integer, Integer>>("get") {
int test(Map<Integer, Integer> map, TestParam testParam) {
int loops = testParam.loops;
int size = testParam.size * 2;
for (int i = 0; i < loops; ++i) {
for (int j = 0; j < size; ++j) {
map.get(j);
}
}
return loops * size;
}
});
tests.add(new Test<Map<Integer, Integer>>("iterate") {
int test(Map<Integer, Integer> map, TestParam testParam) {
int loops = testParam.loops * 10;
for (int i = 0; i < loops; ++i) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
iterator.next();
}
}
return loops * map.size();
}
});
}

public static void main(String[] args) {
if (args.length > 0) {
Tester.defaultTestParams = TestParam.array(args);
}
Tester.run(new HashMap<Integer, Integer>(), tests);
Tester.run(new TreeMap<Integer, Integer>(), tests);
Tester.run(new LinkedHashMap<Integer, Integer>(), tests);
Tester.run(new IdentityHashMap<Integer, Integer>(), tests);
Tester.run(new WeakHashMap<Integer, Integer>(), tests);
Tester.run(new Hashtable<Integer, Integer>(), tests);
Tester.run(new SlowMap<Integer, Integer>(), tests);
}
}
4 changes: 4 additions & 0 deletions ContainersInDepth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,7 @@ because an `ArrayList` must create space and copy all its references forward dur
2. `TreeSet` is used for sorted set.

3. `LinkedHashSet` is for maintaining inserted order.

## Chossing between Maps
When you are using a `Map`, your first choice should be `HashMap`,
and only if you need a constantly sorted `Map` will you need `TreeMap`.

0 comments on commit 6f58cd0

Please sign in to comment.