Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read BufferedReader faster

I want to optimize this code:

InputStream is = rp.getEntity().getContent();        BufferedReader reader = new BufferedReader(new InputStreamReader(is));  String text = ""; String aux = "";  while ((aux = reader.readLine()) != null) {         text += aux;       } 

The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above. I need to spend as little time as possible. Thank you

like image 914
Cata Avatar asked Jan 12 '11 08:01

Cata


People also ask

Is BufferedReader faster?

BufferedReader is a bit faster as compared to scanner because the scanner does the parsing of input data and BufferedReader simply reads a sequence of characters.

How fast is BufferedReader in java?

In an earlier post, I asked how fast the getline function in C++ could run through the lines in a text file. The answer was about 2 GB/s, certainly over 1 GB/s.

Why BufferedReader is faster than FileReader?

Whereas, BufferedReader creates a buffer, and reads large amount of data using the given FileReader and loads it into a input buffer in the memory. Each time you want to read the file data, you can read it from the buffer( you don't have to directly access the disk drive every time) and hence is faster than FileReader.

Which is better Scanner or BufferedReader?

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.


1 Answers

Using string concatenation in a loop is the classic performance killer (because Strings are immutable, the entire, increasingly large String is copied for each concatenation). Do this instead:

StringBuilder builder = new StringBuilder(); String aux = "";  while ((aux = reader.readLine()) != null) {     builder.append(aux); }  String text = builder.toString(); 
like image 63
Michael Borgwardt Avatar answered Sep 21 '22 03:09

Michael Borgwardt