1/*
2 * Copyright (C) 2009 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 examples;
18
19import com.google.caliper.Benchmark;
20import com.google.caliper.Param;
21
22/**
23 * Measures the various ways the JDK converts doubles to strings.
24 */
25public class DoubleToStringBenchmark2 {
26  @Param boolean useWrapper;
27
28  enum Value {
29    Pi(Math.PI),
30    NegativeZero(-0.0),
31    NegativeInfinity(Double.NEGATIVE_INFINITY),
32    NaN(Double.NaN);
33
34    final double d;
35
36    Value(double d) {
37      this.d = d;
38    }
39  }
40
41  @Param Value value;
42
43  @Benchmark int toString(int reps) {
44    int dummy = 0;
45    if (useWrapper) {
46      Double d = value.d;
47      for (int i = 0; i < reps; i++) {
48        dummy += d.toString().length();
49      }
50    } else {
51      double d = value.d;
52      for (int i = 0; i < reps; i++) {
53        dummy += ((Double) d).toString().length();
54      }
55    }
56    return dummy;
57  }
58
59  @Benchmark int stringValueOf(int reps) {
60    int dummy = 0;
61    if (useWrapper) {
62      Double d = value.d;
63      for (int i = 0; i < reps; i++) {
64        dummy += String.valueOf(d).length();
65      }
66    } else {
67      double d = value.d;
68      for (int i = 0; i < reps; i++) {
69        dummy += String.valueOf(d).length();
70      }
71    }
72    return dummy;
73  }
74
75  @Benchmark int stringFormat(int reps) {
76    int dummy = 0;
77    if (useWrapper) {
78      Double d = value.d;
79      for (int i = 0; i < reps; i++) {
80        dummy += String.format("%f", d).length();
81      }
82    } else {
83      double d = value.d;
84      for (int i = 0; i < reps; i++) {
85        dummy += String.format("%f", d).length();
86      }
87    }
88    return dummy;
89  }
90
91  @Benchmark int quoteTrick(int reps) {
92    int dummy = 0;
93    if (useWrapper) {
94      Double d = value.d;
95      for (int i = 0; i < reps; i++) {
96        dummy += ("" + d).length();
97      }
98    } else {
99      double d = value.d;
100      for (int i = 0; i < reps; i++) {
101        dummy += ("" + d).length();
102      }
103    }
104    return dummy;
105  }
106}
107