1 /*
2  * Copyright (C) 2019 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 public class StringBuilderAppendBenchmark {
18     public static String string1 = "s1";
19     public static String string2 = "s2";
20     public static String longString1 = "This is a long string 1";
21     public static String longString2 = "This is a long string 2";
22     public static int int1 = 42;
23 
timeAppendStrings(int count)24     public void timeAppendStrings(int count) {
25         String s1 = string1;
26         String s2 = string2;
27         int sum = 0;
28         for (int i = 0; i < count; ++i) {
29             String result = s1 + s2;
30             sum += result.length();  // Make sure the append is not optimized away.
31         }
32         if (sum != count * (s1.length() + s2.length())) {
33             throw new AssertionError();
34         }
35     }
36 
timeAppendLongStrings(int count)37     public void timeAppendLongStrings(int count) {
38         String s1 = longString1;
39         String s2 = longString2;
40         int sum = 0;
41         for (int i = 0; i < count; ++i) {
42             String result = s1 + s2;
43             sum += result.length();  // Make sure the append is not optimized away.
44         }
45         if (sum != count * (s1.length() + s2.length())) {
46             throw new AssertionError();
47         }
48     }
49 
timeAppendStringAndInt(int count)50     public void timeAppendStringAndInt(int count) {
51         String s1 = string1;
52         int i1 = int1;
53         int sum = 0;
54         for (int i = 0; i < count; ++i) {
55             String result = s1 + i1;
56             sum += result.length();  // Make sure the append is not optimized away.
57         }
58         if (sum != count * (s1.length() + Integer.toString(i1).length())) {
59             throw new AssertionError();
60         }
61     }
62 }
63