在 Java 中从 System.in 读取的最快方法是什么? [英] What's the fastest way to read from System.in in Java?
问题描述
我正在使用 Scanner(System.in)
从标准中读取由空格或换行符分隔的一堆整数.
I am reading bunch of integers separated by space or newlines from the standard in using Scanner(System.in)
.
在 Java 中是否有更快的方法?
Is there any faster way of doing this in Java?
推荐答案
在 Java 中是否有更快的方法?
是的.扫描仪相当慢(至少根据我的经验).
Yes. Scanner is fairly slow (at least according to my experience).
如果您不需要验证输入,我建议您将流包装在 BufferedInputStream 中并使用类似 String.split
/Integer.parseInt
的内容.
If you don't need to validate the input, I suggest you just wrap the stream in a BufferedInputStream and use something like String.split
/ Integer.parseInt
.
一个小的比较:
使用此代码读取 17 兆字节(4233600 个数字)
Reading 17 megabytes (4233600 numbers) using this code
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
sum += scanner.nextInt();
在我的机器上3.3 秒.而这个片段
took on my machine 3.3 seconds. while this snippet
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = bi.readLine()) != null)
for (String numStr: line.split("\s"))
sum += Integer.parseInt(numStr);
用了 0.7 秒.
通过进一步弄乱代码(使用 String.indexOf
/String.substring
遍历 line
),您可以将其缩减为大约0.1 秒很容易,但我想我已经回答了你的问题,我不想把它变成一些代码高尔夫球.
By messing up the code further (iterating over line
with String.indexOf
/ String.substring
) you can get it down to about 0.1 seconds quite easily, but I think I've answered your question and I don't want to turn this into some code golf.
这篇关于在 Java 中从 System.in 读取的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!