Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster in Java for reading/parsing console input, Scanner or BufferedReader?

I have to craft a data processor able to process more than 2.5MB/s of input from STDIN, and output a number to STDOUT. What is faster, to use a BufferedReader and then conversions to data types or a Scanner and nextInt() or nextFloat()?

EMPIRICAL TEST RESULTS: BufferedReader and conversion is a little bit faster, but nothing too significant.

Thankyou!

like image 930
dagilpe Avatar asked Sep 24 '11 10:09

dagilpe


2 Answers

The answer is most likely that it doesn't matter which way you do it from a performance perspective. (And there's no way that someone can type at 2.5Mb per second at the console!)

If you include everything that goes on at the OS level and elsewhere when reading from the console, orders of magnitude more CPU cycles will be expended in getting the bytes from the user typing at the console than are spent parsing the characters. If you are reading from a file (via stdin), we are no longer talking orders of magnitude difference, but I'd still be surprised if the two approaches were significantly different ... overall.

But the best thing you can do is try it out. It shouldn't take more than a few minutes to write a benchmark that roughly approximates to what you are doing, and see which alternative is faster ... and by how much. (Make sure that you measure total elapsed time, not just user-space CPU time for the Java application.)

like image 73
Stephen C Avatar answered Oct 18 '22 13:10

Stephen C


BufferedReader reads the stream. While a Scanner breaks its input into tokens.

2.5MB/s is more suitable for the BufferedReader. It has a larger buffer than Scanner. 8 to 1

BufferedReader >>>>

like image 28
Mob Avatar answered Oct 18 '22 14:10

Mob