Created
May 24, 2011 19:00
-
-
Save sfussenegger/989397 to your computer and use it in GitHub Desktop.
simple experiment for http://stackoverflow.com/questions/6114697/what-would-be-the-fastest-way-to-read-integers-from-a-file-in-java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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