• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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.collect;
18 
19 import com.google.caliper.BeforeExperiment;
20 import com.google.caliper.Benchmark;
21 import com.google.caliper.Param;
22 import com.google.common.collect.BenchmarkHelpers.SetImpl;
23 import com.google.common.collect.CollectionBenchmarkSampleData.Element;
24 
25 import java.util.Set;
26 
27 /**
28  * A microbenchmark that tests the performance of contains() on various Set
29  * implementations.
30  *
31  * @author Kevin Bourrillion
32  */
33 public class SetContainsBenchmark {
34   // Start at 4.88 then multiply by 2*2^phi <evil cackle> - The goal is be uniform
35   // yet visit a variety of "values-relative-to-the-next-power-of-2"
36   @Param({"5", "30", "180", "1100", "6900", "43000", "260000"}) // "1600000", "9800000"
37   private int size;
38 
39   // TODO(kevinb): look at exact (==) hits vs. equals() hits?
40   @Param({"0.2", "0.8"})
41   private double hitRate;
42 
43   @Param("true")
44   private boolean isUserTypeFast;
45 
46   // "" means no fixed seed
47   @Param("")
48   private SpecialRandom random;
49 
50   @Param({"Hash", "Immutable"})
51   private SetImpl impl;
52 
53   // the following must be set during setUp
54   private Element[] queries;
55   private Set<Element> setToTest;
56 
setUp()57   @BeforeExperiment void setUp() {
58     CollectionBenchmarkSampleData sampleData =
59         new CollectionBenchmarkSampleData(
60             isUserTypeFast, random, hitRate, size);
61 
62     this.setToTest = impl.create(sampleData.getValuesInSet());
63     this.queries = sampleData.getQueries();
64   }
65 
contains(int reps)66   @Benchmark boolean contains(int reps) {
67     // Paranoia: acting on hearsay that accessing fields might be slow
68     // Should write a benchmark to test that!
69     Set<Element> set = setToTest;
70     Element[] queries = this.queries;
71 
72     int mask = queries.length - 1;
73 
74     boolean dummy = false;
75     for (int i = 0; i < reps; i++) {
76       dummy ^= set.contains(queries[i & mask]);
77     }
78     return dummy;
79   }
80 }
81