简体   繁体   中英

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.

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? Both of them are reading and parsing, so why is the BufferedReader still quicker?

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?

BufferReader has large buffer of 8KB byte Buffer as compared to Scanner. Scanner is bit slower as it need to parse data as well. BufferReader is faster than Scanner as it only reads a character stream

Difference bettween bufferReader VS scanner

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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