HashedCollectionsBenchmark.java revision 5a7833b406bb2716b057d3ed923f22f1f86b2a20
1/*
2 * Copyright (C) 2010 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package benchmarks;
18
19import com.google.caliper.Param;
20import com.google.caliper.Runner;
21import com.google.caliper.SimpleBenchmark;
22
23import java.util.concurrent.ConcurrentHashMap;
24import java.util.HashMap;
25import java.util.Hashtable;
26import java.util.LinkedHashMap;
27
28/**
29 * How do the various hash maps compare?
30 */
31public class HashedCollectionsBenchmark extends SimpleBenchmark {
32    public void timeHashMapGet(int reps) {
33        HashMap<String, String> map = new HashMap<String, String>();
34        map.put("hello", "world");
35        for (int i = 0; i < reps; ++i) {
36            map.get("hello");
37        }
38    }
39    public void timeHashMapGet_Synchronized(int reps) {
40        HashMap<String, String> map = new HashMap<String, String>();
41        synchronized (map) {
42            map.put("hello", "world");
43        }
44        for (int i = 0; i < reps; ++i) {
45            synchronized (map) {
46                map.get("hello");
47            }
48        }
49    }
50    public void timeHashtableGet(int reps) {
51        Hashtable<String, String> map = new Hashtable<String, String>();
52        map.put("hello", "world");
53        for (int i = 0; i < reps; ++i) {
54            map.get("hello");
55        }
56    }
57    public void timeLinkedHashMapGet(int reps) {
58        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
59        map.put("hello", "world");
60        for (int i = 0; i < reps; ++i) {
61            map.get("hello");
62        }
63    }
64    public void timeConcurrentHashMapGet(int reps) {
65        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
66        map.put("hello", "world");
67        for (int i = 0; i < reps; ++i) {
68            map.get("hello");
69        }
70    }
71}
72