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
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With