OnJava8-Examples/collectionsindepth/MapPerformance.java

83 lines
2.4 KiB
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// collectionsindepth/MapPerformance.java
// (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:
// {Args: 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
100 86 47 9
2015-06-15 17:47:35 -07:00
---------- HashMap ----------
2015-12-15 11:47:04 -08:00
size put get iterate
100 25 10 12
2015-06-15 17:47:35 -07:00
------- LinkedHashMap -------
2015-12-15 11:47:04 -08:00
size put get iterate
100 27 8 6
2015-06-15 17:47:35 -07:00
------ IdentityHashMap ------
2015-12-15 11:47:04 -08:00
size put get iterate
100 51 47 13
2015-06-15 17:47:35 -07:00
-------- WeakHashMap --------
2015-12-15 11:47:04 -08:00
size put get iterate
100 28 11 12
2015-06-15 17:47:35 -07:00
--------- Hashtable ---------
2015-12-15 11:47:04 -08:00
size put get iterate
100 31 21 13
2015-09-07 11:44:36 -06:00
*/