本文介绍了如何更快地读取 BufferedReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想优化这段代码:

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

推荐答案

在循环中使用字符串连接是 经典的性能杀手(因为字符串是不可变的,整个、越来越大的字符串被复制到每个串联).改为这样做:

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

这篇关于如何更快地读取 BufferedReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 08:24