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 17 package examples; 18 19 import com.google.caliper.Benchmark; 20 import java.util.Formatter; 21 22 /** 23 * Compares Formatter against hand-written StringBuilder code. 24 */ 25 public class FormatterBenchmark { 26 @Benchmark void formatter_NoFormatting(int reps) { 27 for (int i = 0; i < reps; i++) { 28 Formatter f = new Formatter(); 29 f.format("this is a reasonably short string that doesn't actually need any formatting"); 30 f.close(); 31 } 32 } 33 34 @Benchmark void stringBuilder_NoFormatting(int reps) { 35 for (int i = 0; i < reps; i++) { 36 StringBuilder sb = new StringBuilder(); 37 sb.append("this is a reasonably short string that doesn't actually need any formatting"); 38 } 39 } 40 41 @Benchmark void formatter_OneInt(int reps) { 42 for (int i = 0; i < reps; i++) { 43 Formatter f = new Formatter(); 44 f.format("this is a reasonably short string that has an int %d in it", i); 45 f.close(); 46 } 47 } 48 49 @Benchmark void stringBuilder_OneInt(int reps) { 50 for (int i = 0; i < reps; i++) { 51 StringBuilder sb = new StringBuilder(); 52 sb.append("this is a reasonably short string that has an int "); 53 sb.append(i); 54 sb.append(" in it"); 55 } 56 } 57 58 @Benchmark void formatter_OneString(int reps) { 59 for (int i = 0; i < reps; i++) { 60 Formatter f = new Formatter(); 61 f.format("this is a reasonably short string that has a string %s in it", "hello"); 62 f.close(); 63 } 64 } 65 66 @Benchmark void stringBuilder_OneString(int reps) { 67 for (int i = 0; i < reps; i++) { 68 StringBuilder sb = new StringBuilder(); 69 sb.append("this is a reasonably short string that has a string "); 70 sb.append("hello"); 71 sb.append(" in it"); 72 } 73 } 74 } 75