1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.lang3;
19
20 import java.util.concurrent.ThreadLocalRandom;
21 import java.util.concurrent.TimeUnit;
22
23 import org.openjdk.jmh.annotations.Benchmark;
24 import org.openjdk.jmh.annotations.BenchmarkMode;
25 import org.openjdk.jmh.annotations.Level;
26 import org.openjdk.jmh.annotations.Mode;
27 import org.openjdk.jmh.annotations.OutputTimeUnit;
28 import org.openjdk.jmh.annotations.Param;
29 import org.openjdk.jmh.annotations.Scope;
30 import org.openjdk.jmh.annotations.Setup;
31 import org.openjdk.jmh.annotations.State;
32
33 @BenchmarkMode(Mode.AverageTime)
34 @OutputTimeUnit(TimeUnit.NANOSECONDS)
35 @State(Scope.Thread)
36 public class StringUtilsGetDigitsBenchmark {
37
38 public static String getDigitsManually(final String str) {
39 if (StringUtils.isEmpty(str)) {
40 return str;
41 }
42 final int len = str.length();
43 final char[] buffer = new char[len];
44 int count = 0;
45 for (int i = 0; i < len; i++) {
46 final char tempChar = str.charAt(i);
47 if (Character.isDigit(tempChar)) {
48 buffer[count++] = tempChar;
49 }
50 }
51 return new String(buffer, 0, count);
52 }
53 public static String getDigitsWithBuilder(final String str) {
54 if (StringUtils.isEmpty(str)) {
55 return str;
56 }
57 final int sz = str.length();
58 final StringBuilder strDigits = new StringBuilder(sz);
59 for (int i = 0; i < sz; i++) {
60 final char tempChar = str.charAt(i);
61 if (Character.isDigit(tempChar)) {
62 strDigits.append(tempChar);
63 }
64 }
65 return strDigits.toString();
66 }
67
68 @Param({ "10", "100", "1000", "10000" })
69 public int length;
70
71 private String testStr;
72
73 @Setup(Level.Invocation)
74 public void setup() {
75 final StringBuilder sb = new StringBuilder(length);
76 for (int i = 0; i < length; i++) {
77 final int code = ThreadLocalRandom.current().nextInt(33, 127);
78 sb.append((char) code);
79 }
80 testStr = sb.toString();
81 }
82
83 @Benchmark
84 public String testGetDigitsManually() {
85 return getDigitsManually(testStr);
86 }
87
88 @Benchmark
89 public String testGetDigitsWithBuilder() {
90 return getDigitsWithBuilder(testStr);
91 }
92 }