BufferedReader vs Scanner in Java: Performance Comparison

Most of us, when we started Competitive Programming in Java, understood that using the Scanner class for taking inputs and System.out.print() for outputs can make our programs slower, so we quickly switched to BufferedReader and BufferedWriter by following a standard template, which improved the execution time. I decided to understand both to see how they differ and what makes the latter one faster. Honestly, the logic was simple. BufferedReader and BufferedWriter use a buffer to store a large chunk of an input stream in a single I/O operation, then break it up internally according to the needs, using a StringTokenizer or any other means.   Scanner does internal parsing and reads input token by token. It performs extra processing like regex matching, which makes it convenient but slower. It also takes care of token validation internally. BufferedReader works differently. It reads a large chunk of data into memory at once (a buffer) and then processes it. Instead of interacting with the input stream repeatedly, it reduces the system calls made. It just reads the stream and does not do any special parsing. Moreover, Scanner is also not thread safe.   This doesn’t mean Buffered Reader is better than Scanner in any way, though; it depends on specific use cases and what we want.   I decided to learn Java I/O properly and tried to understand how input/output streams and reader/writer classes work. It was fun. 😊 It fascinates me how engineers have tailored systems with clever techniques for several use cases. Happy Coding :)   #Java #Coding #CompetitiveProgramming #SoftwareEngineering

  • graphical user interface, website

Thanks for sharing 😊👍🏻

To view or add a comment, sign in

Explore content categories