Skip to content

Instantly share code, notes, and snippets.

@sfussenegger
Created May 24, 2011 19:00
Show Gist options
  • Save sfussenegger/989397 to your computer and use it in GitHub Desktop.
Save sfussenegger/989397 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.StringReader;
import java.util.Random;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) throws IOException {
int chars = (37 * 1000 * 1000);
StringBuilder buf = new StringBuilder(chars);
Random rand = new Random();
System.out.println("start appending " + chars + " chars");
while (buf.length() < chars) {
buf.append(rand.nextInt(9999)).append(" ");
}
System.out.println("buf to string");
String str = buf.toString();
for (int round = 0; round < 5; round++) {
Scanner scan = new Scanner(str);
long sum = 0;
System.out.println("scanning");
long start = System.currentTimeMillis();
while (scan.hasNext()) {
sum += scan.nextInt();
}
long time = System.currentTimeMillis() - start;
System.out.println("finished " + time + "ms " + sum);
System.out.println("reading");
StringReader r = new StringReader(str);
sum = 0;
int next;
int current = 0;
while ((next = r.read()) > 0) {
if (next == ' ') {
sum += current;
current = 0;
} else {
current = current * 10 + (next - '0');
}
}
time = System.currentTimeMillis() - start;
System.out.println("finished " + time + "ms " + sum);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment