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.base;
18 
19 import com.google.caliper.Benchmark;
20 import com.google.caliper.Param;
21 
22 /**
23  * Some microbenchmarks for the {@link MoreObjects.ToStringHelper} class.
24  *
25  * @author Osvaldo Doederlein
26  */
27 public class ToStringHelperBenchmark {
28 
29   @Param({"0", "2", "5", "10"})
30   int dataSize;
31 
32   private static final String NAME = "abcdefgh";
33   private static final String NAME3 = Strings.repeat(NAME, 3);
34 
addEntries(MoreObjects.ToStringHelper helper)35   private static void addEntries(MoreObjects.ToStringHelper helper) {
36     helper
37         .add(NAME, 10)
38         .addValue(10L)
39         .add(NAME, 3.14f)
40         .addValue(3.14d)
41         .add(NAME3, false)
42         .add(NAME3, NAME3)
43         .add(NAME3, 'x');
44   }
45 
46   @Benchmark
toString(int reps)47   int toString(int reps) {
48     int dummy = 0;
49     for (int i = 0; i < reps; i++) {
50       MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper("klass").omitNullValues();
51       for (int j = 0; j < dataSize; ++j) {
52         addEntries(helper);
53       }
54       dummy ^= helper.toString().hashCode();
55     }
56     return dummy;
57   }
58 }
59