1   /*
2    * StringIterator
3    * Copyright (C) 2008 Christian Schenk
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    * 
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   * 
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
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  		// does almost nothing
84  		int i = c; i++;
85  	}
86  }