1 /* 2 * Copyright (C) 2016 The Android Open Source Project 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.regression; 18 19 import com.google.caliper.Param; 20 21 import java.nio.charset.StandardCharsets; 22 23 public class StringToBytesBenchmark { 24 static enum StringLengths { 25 EMPTY(""), 26 L_16(makeString(16)), 27 L_64(makeString(64)), 28 L_256(makeString(256)), 29 L_512(makeString(512)), 30 A_16(makeAsciiString(16)), 31 A_64(makeAsciiString(64)), 32 A_256(makeAsciiString(256)), 33 A_512(makeAsciiString(512)); 34 35 private final String value; 36 StringLengths(String s)37 private StringLengths(String s) { 38 this.value = s; 39 } 40 } 41 makeString(int length)42 private static final String makeString(int length) { 43 char[] chars = new char[length]; 44 for (int i = 0; i < length; ++i) { 45 chars[i] = (char) i; 46 } 47 return new String(chars); 48 } 49 makeAsciiString(int length)50 private static final String makeAsciiString(int length) { 51 char[] chars = new char[length]; 52 for (int i = 0; i < length; ++i) { 53 chars[i] = ((i & 0x7f) != 0) ? (char) (i & 0x7f) : '?'; 54 } 55 return new String(chars); 56 } 57 58 @Param StringLengths string; 59 timeGetBytesUtf8(int nreps)60 public void timeGetBytesUtf8(int nreps) { 61 for (int i = 0; i < nreps; ++i) { 62 string.value.getBytes(StandardCharsets.UTF_8); 63 } 64 } 65 timeGetBytesIso88591(int nreps)66 public void timeGetBytesIso88591(int nreps) { 67 for (int i = 0; i < nreps; ++i) { 68 string.value.getBytes(StandardCharsets.ISO_8859_1); 69 } 70 } 71 timeGetBytesAscii(int nreps)72 public void timeGetBytesAscii(int nreps) { 73 for (int i = 0; i < nreps; ++i) { 74 string.value.getBytes(StandardCharsets.US_ASCII); 75 } 76 } 77 } 78