-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample106.java
More file actions
52 lines (46 loc) · 1.68 KB
/
Example106.java
File metadata and controls
52 lines (46 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Example 106 from page 79
//
import java.util.Random;
class Example106 {
public static void main(String[] args) {
if (args.length != 1)
System.out.println("Usage: java Example106 <length>\n");
else {
System.out.println("Timing character replacement, abusing a string buffer:");
Random rnd = new Random();
int length = Integer.parseInt(args[0]);
char[] cbuf = new char[length];
for (int i=0; i<length; i++)
cbuf[i] = (char)(65 + rnd.nextInt(26));
String s = new String(cbuf);
for (int i=0; i<10; i++) {
StringBuilder sb = new StringBuilder(s);
Timer t = new Timer();
replaceCharString(sb, 'A', "HA");
System.out.print(t.check() + " ");
}
System.out.println();
}
}
// In-place replacement in a StringBuilder; very inefficient and strange
static void replaceCharString(StringBuilder sb, char c1, String s2) {
int i = 0; // Inefficient
while (i < sb.length()) { // Inefficient
if (sb.charAt(i) == c1) { // Inefficient
sb.replace(i, i+1, s2); // Inefficient
i += s2.length(); // Inefficient
} else // Inefficient
i += 1; // Inefficient
} // Inefficient
}
// Simple timer, measuring wall-clock (elapsed) time in seconds
private final static class Timer {
private long start;
public Timer() {
start = System.nanoTime();
}
public double check() {
return (System.nanoTime() - start)/1e9;
}
}
}