1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.codec.language.bm;
19
20 import org.junit.jupiter.api.Test;
21
22 public class CacheSubSequencePerformanceTest {
23
24 private CharSequence cacheSubSequence(final CharSequence cached) {
25 final CharSequence[][] cache = new CharSequence[cached.length()][cached.length()];
26 return new CharSequence() {
27 @Override
28 public char charAt(final int index) {
29 return cached.charAt(index);
30 }
31
32 @Override
33 public int length() {
34 return cached.length();
35 }
36
37 @Override
38 public CharSequence subSequence(final int start, final int end) {
39 if (start == end) {
40 return "";
41 }
42 CharSequence res = cache[start][end - 1];
43 if (res == null) {
44 res = cached.subSequence(start, end);
45 cache[start][end - 1] = res;
46 }
47 return res;
48 }
49 };
50 }
51
52 @Test
53 public void test() {
54 final int times = 10000000;
55 System.out.print("Test with String : ");
56 test("Angelo", times);
57 System.out.print("Test with StringBuilder : ");
58 test(new StringBuilder("Angelo"), times);
59 System.out.print("Test with cached String : ");
60 test(cacheSubSequence("Angelo"), times);
61 System.out.print("Test with cached StringBuilder : ");
62 test(cacheSubSequence(new StringBuilder("Angelo")), times);
63 }
64
65 private void test(final CharSequence input) {
66 for (int i = 0; i < input.length(); i++) {
67 for (int j = i; j <= input.length(); j++) {
68 input.subSequence(i, j);
69 }
70 }
71 }
72
73 private void test(final CharSequence input, final int times) {
74 final long beginTimeMillis = System.currentTimeMillis();
75 for (int i = 0; i < times; i++) {
76 test(input);
77 }
78 System.out.println(System.currentTimeMillis() - beginTimeMillis + " millis");
79 }
80 }