1 /* 2 * Copyright (C) 2010 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 benchmarks; 18 19 import com.google.caliper.Param; 20 import com.google.caliper.Runner; 21 import com.google.caliper.SimpleBenchmark; 22 23 /** 24 * How do the various schemes for iterating through a string compare? 25 */ 26 public class StringIterationBenchmark extends SimpleBenchmark { timeStringIteration0(int reps)27 public void timeStringIteration0(int reps) { 28 String s = "hello, world!"; 29 for (int rep = 0; rep < reps; ++rep) { 30 char ch; 31 for (int i = 0; i < s.length(); ++i) { 32 ch = s.charAt(i); 33 } 34 } 35 } timeStringIteration1(int reps)36 public void timeStringIteration1(int reps) { 37 String s = "hello, world!"; 38 for (int rep = 0; rep < reps; ++rep) { 39 char ch; 40 for (int i = 0, length = s.length(); i < length; ++i) { 41 ch = s.charAt(i); 42 } 43 } 44 } timeStringIteration2(int reps)45 public void timeStringIteration2(int reps) { 46 String s = "hello, world!"; 47 for (int rep = 0; rep < reps; ++rep) { 48 char ch; 49 char[] chars = s.toCharArray(); 50 for (int i = 0, length = chars.length; i < length; ++i) { 51 ch = chars[i]; 52 } 53 } 54 } timeStringToCharArray(int reps)55 public void timeStringToCharArray(int reps) { 56 String s = "hello, world!"; 57 for (int rep = 0; rep < reps; ++rep) { 58 char[] chars = s.toCharArray(); 59 } 60 } 61 } 62