0

I am trying to read a response from server using HttpsURLConnection.

InputStreamReader in = new InputStreamReader((InputStream) con.getContent());
    BufferedReader buff = new BufferedReader(in);

    String line;
    StringBuilder response=new StringBuilder();
    long st=System.nanoTime();

    while ((line =buff.readLine())!= null) {
        response=response.append(line +"\n");

    } 

    long et=System.nanoTime();
    System.out.println("resp process time: "+((et-st))+" ns");
    return response.toString();
}

Currently, it takes approximately 450 ms to read the entire response consisting about 80000 characters( 1100 lines).

Output: resp process time: 435272240 ns

Would it be possible to optimize this code further to reduce processing time?

Akki
  • 112
  • 12
  • possible duplicate of [Java: how to read BufferedReader faster](http://stackoverflow.com/questions/4666748/java-how-to-read-bufferedreader-faster) –  Jul 19 '15 at 12:20
  • @OSryx Not exactly a duplicate, as this one here uses a `StringBuilder`. – RealSkeptic Jul 19 '15 at 12:22

1 Answers1

1

You create an unnecessary temporary string line + "\n". You can avoid this.

while ((line = buff.readLine()) != null) {
    response.append(line).append('\n');
} 

You can also avoid the BufferedReader (no need to scan the input for linebreaks).

InputStreamReader in = ...
char buffer[] = new char[8192];
int count;
while ((count = in.read(buffer)) != -1)
    response.append(buffer, 0, count);
wero
  • 32,544
  • 3
  • 59
  • 84
  • +1 for the part where you use a char[] instead of `BufferedReader`. I personally prefer this option if you are not doing any processing on each line. Might cause problems if input size is too large :P – TheLostMind Jul 19 '15 at 12:28
  • size of the response from server is not fixed and can differ greatly with each request, so this solution is correct but not appropriate for this particular scenario – Akki Jul 19 '15 at 12:37
  • @Akki: BufferedReader also has a default buffer of 8192 chars, so memory characteristics are the same for both solutions. Of course, if the response sends a content-length header and encoding you could estimate the size of response buffer and any temporary buffer for copying. – wero Jul 19 '15 at 12:42