[英]Optimize BufferedReader readLine() operations
I am trying to read a response from server using HttpsURLConnection
. 我正在尝试使用
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). 当前,读取整个响应大约需要450毫秒,包括大约80000个字符(1100行)。
Output: resp process time: 435272240 ns 输出:响应处理时间:435272240 ns
Would it be possible to optimize this code further to reduce processing time? 是否可以进一步优化此代码以减少处理时间?
You create an unnecessary temporary string line + "\\n"
. 您创建了不必要的临时字符串
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). 您也可以避免使用BufferedReader(无需扫描输入中的换行符)。
InputStreamReader in = ...
char buffer[] = new char[8192];
int count;
while ((count = in.read(buffer)) != -1)
response.append(buffer, 0, count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.