使用 BufferedReader.readLine() 读取 inputStream 的速度太慢

2022-09-01 02:42:34

我正在使用以下代码。

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;

StringBuilder responseData = new StringBuilder();
while((line = in.readLine()) != null) {
    responseData.append(line);
}

但是读取200行需要超过12秒的时间。

请帮忙


答案 1

我强烈怀疑这是因为网络连接或您正在与之交谈的Web服务器 - 这不是“的错。尝试测量以下内容:BufferedReader

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

我想你会发现它几乎与你解析文本的时间完全相同。

请注意,您还应该提供适当的编码 - 平台默认编码几乎肯定不是您应该使用的编码。InputStreamReader


答案 2

我有一个更长的测试要尝试。这平均需要160 ns来读取每行,因为它添加到List(这可能是你想要的,因为删除换行符不是很有用。

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

指纹

Average time to read a line was 158 ns.

如果你想构建一个StringBuilder,保留换行符,我会采用以下方法。

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

静止印刷品

Average time to read a line was 159 ns.

在这两种情况下,速度都受到发送方而不是接收方的限制。通过优化发送器,我将此时序降低到每行105 ns。


推荐