简体   繁体   English

为什么 BufferedReader 比 Scanner 快?

[英]Why BufferedReader is faster than Scanner?

I know that using a BufferedReader is quicker than using a Scanner since the Scanner reads and parses the Stream while the BufferedReader only reads the Stream.我知道使用BufferedReader比使用Scanner更快,因为Scanner读取并解析 Stream 而BufferedReader仅读取 Stream。

However, I do not understand why the BufferedReader would still be quicker if I'm parsing the Stream after reading it from the BufferedReader , wouldn't this be essentially the same thing the Scanner is doing?但是,我不明白为什么在从BufferedReader读取 Stream 后解析 Stream 时,为什么BufferedReader仍然会更快,这与Scanner所做的基本相同吗? Both of them are reading and parsing, so why is the BufferedReader still quicker?他们都在读取和解析,那么为什么BufferedReader仍然更快呢?

Let's say I'm taking integers as an input:假设我将整数作为输入:

public static void main(String[] args) throws IOException {

   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

   int x = Integer.parseInt(br.readLine());
   System.out.println(x);

   }

Won't this be the same as this:这会不会和这个一样:

public static void main(String[] args) throws IOException {

   Scanner sc = new Scanner(System.in);
   int x = sc.nextInt();
   System.out.println(x);

   }
  1. So is my understanding of how this works correct?那么我对这是如何工作的理解正确吗?
  2. Does the larger buffer size of the BufferedReader also help? BufferedReader更大的缓冲区大小是否也有帮助?

BufferReader has large buffer of 8KB byte Buffer as compared to Scanner.与 Scanner 相比, BufferReader具有8KB 字节Buffer 的大缓冲区。 Scanner is bit slower as it need to parse data as well.扫描仪有点慢,因为它也需要解析数据。 BufferReader is faster than Scanner as it only reads a character stream BufferReader 比 Scanner 快,因为它只读取一个字符 stream

Difference bettween bufferReader VS scanner bufferReader 与扫描仪之间的区别

https://www.tutorialspoint.com/difference-between-scanner-and-bufferreader-class-in-java https://www.tutorialspoint.com/difference-between-scanner-and-bufferreader-class-in-java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM