1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.christianschenk.stringutils;
20
21 import org.christianschenk.stopwatch.StopWatch;
22 import org.junit.Before;
23 import org.junit.Test;
24
25 public class StringIteratorTest {
26
27 private String testString;
28 private final int RUNS = 10;
29
30 @Before
31 public void setup() {
32 this.testString = FileHelper.readFile("test.txt");
33 }
34
35 @Test
36 public void perfTest() {
37 for (final Runnable test : new Runnable[] { stringIterator, toCharArray, charAt, charSequence_charAt }) {
38 int ms = 0;
39 for (int i = 0; i < RUNS; i++) {
40 StopWatch.start();
41 test.run();
42 StopWatch.stop();
43 ms += StopWatch.getResult();
44 }
45 System.out.println("result: " + ((double) ms / RUNS));
46 }
47 }
48
49 private final Runnable stringIterator = new Runnable() {
50 public void run() {
51 for (final char c : new StringIterator(testString)) {
52 doSomething(c);
53 }
54 }
55 };
56
57 private final Runnable toCharArray = new Runnable() {
58 public void run() {
59 for (final char c : testString.toCharArray()) {
60 doSomething(c);
61 }
62 }
63 };
64
65 private final Runnable charAt = new Runnable() {
66 public void run() {
67 for (int i = 0; i < testString.length(); i++) {
68 doSomething(testString.charAt(i));
69 }
70 }
71 };
72
73 private final Runnable charSequence_charAt = new Runnable() {
74 public void run() {
75 final CharSequence charSeq = testString.subSequence(0, testString.length());
76 for (int i = 0; i < testString.length(); i++) {
77 doSomething(charSeq.charAt(i));
78 }
79 }
80 };
81
82 private void doSomething(final char c) {
83
84 int i = c; i++;
85 }
86 }