从Java中读取System.in的最快方法是什么? [英] What's the fastest way to read from System.in in Java?

查看:170
本文介绍了从Java中读取System.in的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读使用 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中有更快的方法吗?

Is there any faster way of doing this in 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 / <$ c $迭代 c> String.substring )你可以很容易地把它降到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆