On 3/20/06, Bryan Sant <[EMAIL PROTECTED]> wrote:
> Java (1.5 using -server)
> ------
> Avg Time: 6.81
> LOC: 25
So, I refactored the Java code to use Java NIO (which is using mmap()
under the covers). Also, I'm using Java 6 instead of 5.
Java (1.6 using -server)
------
Avg Time: 2.92
LOC: 53
The source is attached.
-Bryan
import java.io.*;
import java.nio.*;
import java.util.*;
public class DictWords {
private static ByteBuffer buffer;
private static StringBuilder tmp = new StringBuilder();
private static int i;
public static void main(String[] args) throws Exception {
Map<String, Int> words = new HashMap<String, Int>();
String word;
setupMemoryMap("/usr/share/dict/words");
while ((word = getNextWord()) != null)
words.put(word, new Int());
setupMemoryMap(args[0]);
while ((word = getNextWord()) != null) {
Int entry = words.get(word);
if (entry != null)
entry.value++;
}
tmp.setLength(0);
for (Map.Entry entry : words.entrySet()) {
int count = ((Int) entry.getValue()).value;
if (count > 0)
tmp.append(entry.getKey() + " " + count + "\n");
}
System.out.print(tmp);
}
private static void setupMemoryMap(String filePath) throws Exception {
FileInputStream fis = new FileInputStream(filePath);
buffer = MappedByteBuffer.allocateDirect((int) fis.available());
fis.getChannel().read(buffer);
tmp.setLength(0);
i = 0;
}
private static String getNextWord() {
String s = null;
for (; i < buffer.limit(); i++) {
char c = (char) buffer.get(i);
if (c == ' ' || c == '\n' || c == '\t') {
s = tmp.toString();
tmp.setLength(0);
i++;
break;
}
else
tmp.append(c);
}
return s;
}
static class Int {
int value = 0;
}
}
/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/