How to read BufferedReader faster

Cata picture Cata · Jan 12, 2011 · Viewed 66.2k times · Source

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

Michael Borgwardt picture Michael Borgwardt · Jan 12, 2011

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();