Cata Cata - 1 year ago 180
Java Question

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

Answer Source

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) {

String text = builder.toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download