• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Guava Authors
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 
17 package com.google.common.cache;
18 
19 import com.google.caliper.BeforeExperiment;
20 import com.google.caliper.Benchmark;
21 import com.google.common.collect.MapMaker;
22 import java.util.Map;
23 
24 /**
25  * Compare CacheBuilder and MapMaker performance, ensuring that they remain on par with each other.
26  *
27  * @author Nikita Sidorov
28  */
29 @SuppressWarnings("CheckReturnValue")
30 public class MapMakerComparisonBenchmark {
31   private static final String TEST_KEY = "test key";
32   private static final String TEST_VALUE = "test value";
33 
34   // Non-loading versions:
35   private final Map<Object, Object> map = new MapMaker().makeMap(); // Returns ConcurrentHashMap
36   private final Cache<Object, Object> cache = CacheBuilder.newBuilder().recordStats().build();
37   private final Cache<Object, Object> cacheNoStats = CacheBuilder.newBuilder().build();
38 
39   @BeforeExperiment
setUp()40   void setUp() {
41     map.put(TEST_KEY, TEST_VALUE);
42     cache.put(TEST_KEY, TEST_VALUE);
43     cacheNoStats.put(TEST_KEY, TEST_VALUE);
44   }
45 
46   @Benchmark
concurrentHashMap(int rep)47   void concurrentHashMap(int rep) {
48     for (int i = 0; i < rep; i++) {
49       map.get(TEST_KEY);
50     }
51   }
52 
53   @Benchmark
cacheBuilder_stats(int rep)54   void cacheBuilder_stats(int rep) {
55     for (int i = 0; i < rep; i++) {
56       cache.getIfPresent(TEST_KEY);
57     }
58   }
59 
60   @Benchmark
cacheBuilder(int rep)61   void cacheBuilder(int rep) {
62     for (int i = 0; i < rep; i++) {
63       cacheNoStats.getIfPresent(TEST_KEY);
64     }
65   }
66 }
67