83 lines
2.5 KiB
Java
Raw Normal View History

2016-08-02 11:52:46 -06:00
// understandingcollections/MapPerformance.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Demonstrates performance differences in Maps
2016-07-07 12:43:10 -06:00
// Small to keep build testing short:
2016-07-28 13:42:03 -06:00
// {java MapPerformance 100 5000}
2015-06-15 17:47:35 -07:00
import java.util.*;
public class MapPerformance {
static List<Test<Map<Integer,Integer>>> tests =
new ArrayList<>();
static {
tests.add(new Test<Map<Integer,Integer>>("put") {
@Override
int test(Map<Integer,Integer> map, TestParam tp) {
int loops = tp.loops;
int size = tp.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") {
@Override
int test(Map<Integer,Integer> map, TestParam tp) {
int loops = tp.loops;
int span = tp.size * 2;
for(int i = 0; i < loops; i++)
for(int j = 0; j < span; j++)
map.get(j);
return loops * span;
}
});
tests.add(new Test<Map<Integer,Integer>>("iterate") {
@Override
int test(Map<Integer,Integer> map, TestParam tp) {
int loops = tp.loops * 10;
for(int i = 0; i < loops; i ++) {
Iterator it = map.entrySet().iterator();
while(it.hasNext())
it.next();
}
return loops * map.size();
}
});
}
public static void main(String[] args) {
if(args.length > 0)
Tester.defaultParams = TestParam.array(args);
Tester.run(new TreeMap<>(), tests);
Tester.run(new HashMap<>(), tests);
Tester.run(new LinkedHashMap<>(),tests);
Tester.run(
new IdentityHashMap<>(), tests);
Tester.run(new WeakHashMap<>(), tests);
Tester.run(new Hashtable<>(), tests);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
---------- TreeMap ----------
2015-12-15 11:47:04 -08:00
size put get iterate
2016-07-27 11:12:11 -06:00
100 286 152 35
2015-06-15 17:47:35 -07:00
---------- HashMap ----------
2015-12-15 11:47:04 -08:00
size put get iterate
2016-07-27 11:12:11 -06:00
100 86 38 44
2015-06-15 17:47:35 -07:00
------- LinkedHashMap -------
2015-12-15 11:47:04 -08:00
size put get iterate
2016-07-27 11:12:11 -06:00
100 92 27 28
2015-06-15 17:47:35 -07:00
------ IdentityHashMap ------
2015-12-15 11:47:04 -08:00
size put get iterate
2016-07-27 11:12:11 -06:00
100 298 101 42
2015-06-15 17:47:35 -07:00
-------- WeakHashMap --------
2015-12-15 11:47:04 -08:00
size put get iterate
2016-07-27 11:12:11 -06:00
100 88 36 57
2015-06-15 17:47:35 -07:00
--------- Hashtable ---------
2015-12-15 11:47:04 -08:00
size put get iterate
2016-07-27 11:12:11 -06:00
100 98 52 46
2015-09-07 11:44:36 -06:00
*/