Akki
Akki

Reputation: 122

Optimize BufferedReader readLine() operations

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?

Upvotes: 0

Views: 860

Answers (1)

wero
wero

Reputation: 33010

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

Upvotes: 1

Related Questions