从输入读取时,为什么Scanner比BufferedReader慢? [英] Why is Scanner slower than BufferedReader when reading from input?

查看:414
本文介绍了从输入读取时,为什么Scanner比BufferedReader慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解Scanner的优点,以及何时使用Scanner和BufferedReader。
我读了一个不同的,但在一些类似的问题扫描仪与BufferedReader

I understand what is Scanner good for, and also when to use Scanner and when BufferedReader. I read a different, yet in some therm similar question Scanner vs. BufferedReader

当我从输入读取时为什么Scanner这么慢?
我认为它与Scanner中有一个小缓冲区有关,但在这里我迷失了。
原始问题来自 Codechef ,但我对该解决方案不感兴趣。

Why is Scanner so slow when I read from the input? I assume it has to do with that there is a small buffer in Scanner, but here I am lost. The original problem is from, Codechef , but I am not interested in that solution.

以下是给定输入的代码示例:
输入:

Here is a code example with a given input: Input:


  • 7 3

  • 1

  • 51

  • 966369

  • 7

  • 9

  • 999996

  • 1

  • 7 3
  • 1
  • 51
  • 966369
  • 7
  • 9
  • 999996
  • 1

代码

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s = br.readLine().split(" "); 
        int numberOfLines = Integer.parseInt(s[0]);
        int divideNumber = Integer.parseInt(s[1]);
        int count = 0;

        for (int i = 0; i < numberOfLines; i++) {
            String number = br.readLine();
            if (number.length() < 11) {
                int num = Integer.parseInt(number);
                if (num % divideNumber == 0) {
                    count++;
                }
            } 
        }
        System.out.println(count);
    }
}

如果我用扫描仪读取相同的代码,那就很慢。

If I read the same code with scanner it is slow.

推荐答案

高级类/方法通常比低级类/方法慢。

In你可以问为什么用正常表达式搜索比用$ code搜索 String.indexOf()。实际上我已经在SO上看过这样的问题了。

Upper-level classes/methods are generally slower than lower-level classes/methods.
In the same way you could ask why is searching with regular expressions slower than
searching with String.indexOf(). Actually I've seen such questions here on SO.

你的类/方法越专业,它就越能表现出来。

它确实如此。例如这只是一件简单的事情,但它可以快速有效地完成。

更一般的类/方法可以做到10-20个不同的东西,所以他们的
更强大,但由于这个原因,它们更慢。

The more specialized your class/method is, the better it can perform.
It does e.g. just 1 simple thing but does it quickly and efficiently.
More general classes/methods do e.g. 10-20 different things, so they
are more powerful but due to this they are slower.

我在这里说的一般,我没有比较扫描仪 BufferedReader 我自己。

I am speaking in general here, I haven't compared Scanner and BufferedReader myself.

这篇关于从输入读取时,为什么Scanner比BufferedReader慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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