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.Test;
21
22 public class CacheSubSequencePerformanceTest {
23
24 @Test
25 public void test() {
26 final int times = 10000000;
27 System.out.print("Test with String : ");
28 test("Angelo", times);
29 System.out.print("Test with StringBuilder : ");
30 test(new StringBuilder("Angelo"), times);
31 System.out.print("Test with cached String : ");
32 test(cacheSubSequence("Angelo"), times);
33 System.out.print("Test with cached StringBuilder : ");
34 test(cacheSubSequence(new StringBuilder("Angelo")), times);
35 }
36
37 private void test(final CharSequence input, final int times) {
38 final long beginTime = System.currentTimeMillis();
39 for (int i = 0; i < times; i++) {
40 test(input);
41 }
42 System.out.println(System.currentTimeMillis() - beginTime + " millis");
43 }
44
45 private void test(final CharSequence input) {
46 for (int i = 0; i < input.length(); i++) {
47 for (int j = i; j <= input.length(); j++) {
48 input.subSequence(i, j);
49 }
50 }
51 }
52
53 private CharSequence cacheSubSequence(final CharSequence cached) {
54 final CharSequence[][] cache = new CharSequence[cached.length()][cached.length()];
55 return new CharSequence() {
56 @Override
57 public char charAt(final int index) {
58 return cached.charAt(index);
59 }
60
61 @Override
62 public int length() {
63 return cached.length();
64 }
65
66 @Override
67 public CharSequence subSequence(final int start, final int end) {
68 if (start == end) {
69 return "";
70 }
71 CharSequence res = cache[start][end - 1];
72 if (res == null) {
73 res = cached.subSequence(start, end);
74 cache[start][end - 1] = res;
75 }
76 return res;
77 }
78 };
79 }
80 }