-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample134.java
More file actions
67 lines (55 loc) · 2.17 KB
/
Example134.java
File metadata and controls
67 lines (55 loc) · 2.17 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Example 134 from page 107
//
import java.util.*;
// The HashSet is 3 to 9 times faster than Arrays.binarySearch, even
// for this list of strings of only 52 elements:
class Example134 {
final static String[] keywordarray =
{ "abstract", "assert", "boolean", "break", "byte", "case", "catch",
"char", "class", "const", "continue", "default", "do", "double", "else",
"enum", "extends", "false", "final", "finally", "float", "for", "goto",
"if", "implements", "import", "instanceof", "int", "interface", "long",
"native", "new", "null", "package", "private", "protected", "public",
"return", "short", "static", "strictfp", "super", "switch",
"synchronized", "this", "throw", "throws", "transient", "true",
"try", "void", "volatile", "while" };
final static Set<String> keywords
= new HashSet<String>(Arrays.asList(keywordarray));
static boolean isKeyword1(String id)
{ return keywords.contains(id); }
static boolean isKeyword2(String id)
{ return Arrays.binarySearch(keywordarray, id) >= 0; }
public static void main(String[] args) {
if (args.length != 2)
System.out.println("Usage: java Example134 <iterations> <word>");
else {
final int count = Integer.parseInt(args[0]);
final String id = args[1];
for (int i=0; i<keywordarray.length; i++)
if (isKeyword1(keywordarray[i]) != isKeyword2(keywordarray[i]))
System.out.println("Error at i = " + i);
if (isKeyword1(id) != isKeyword2(id))
System.out.println("Error at id = " + id);
System.out.print("HashSet.contains ");
Timer t1 = new Timer();
for (int i=0; i<count; i++)
isKeyword1(id);
System.out.println(t1.check());
System.out.print("Arrays.binarySearch ");
Timer t2 = new Timer();
for (int i=0; i<count; i++)
isKeyword2(id);
System.out.println(t2.check());
}
}
// 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;
}
}
}