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