我正在使用以下代码。
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秒。
请帮忙
答案 0 :(得分:30)
我强烈怀疑这是因为网络连接或你正在与之交谈的网络服务器 - 这不是BufferedReader
的错。试着测量一下:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
我认为你会发现它几乎与解析文本的时间完全相同。
请注意,您还应该为InputStreamReader
提供适当的编码 - 平台默认编码几乎肯定不您应该使用的内容。
答案 1 :(得分:8)
我有更长的考试要尝试。这需要平均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。