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 DoubleToStringBenchmark { 26 @Param Method method; 27 28 public enum Method { 29 TO_STRING { 30 @Override String convert(double d) { 31 return ((Double) d).toString(); 32 } 33 @Override String convert(Double d) { 34 return d.toString(); 35 } 36 }, 37 STRING_VALUE_OF { 38 @Override String convert(double d) { 39 return String.valueOf(d); 40 } 41 @Override String convert(Double d) { 42 return String.valueOf(d); 43 } 44 }, 45 STRING_FORMAT { 46 @Override String convert(double d) { 47 return String.format("%f", d); 48 } 49 @Override String convert(Double d) { 50 return String.format("%f", d); 51 } 52 }, 53 QUOTE_TRICK { 54 @Override String convert(double d) { 55 return "" + d; 56 } 57 @Override String convert(Double d) { 58 return "" + d; 59 } 60 }, 61 ; 62 63 abstract String convert(double d); 64 abstract String convert(Double d); 65 } 66 67 enum Value { 68 Pi(Math.PI), 69 NegativeZero(-0.0), 70 NegativeInfinity(Double.NEGATIVE_INFINITY), 71 NaN(Double.NaN); 72 73 final double value; 74 75 Value(double value) { 76 this.value = value; 77 } 78 } 79 80 @Param Value value; 81 82 @Benchmark int primitive(int reps) { 83 double d = value.value; 84 int dummy = 0; 85 for (int i = 0; i < reps; i++) { 86 dummy += method.convert(d).length(); 87 } 88 return dummy; 89 } 90 91 @Benchmark int wrapper(int reps) { 92 Double d = value.value; 93 int dummy = 0; 94 for (int i = 0; i < reps; i++) { 95 dummy += method.convert(d).length(); 96 } 97 return dummy; 98 } 99} 100