Java中有效的字符串流输入流 [英] efficient input stream to string method in java

查看:111
本文介绍了Java中有效的字符串流输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在Java中的应用程序上运行了探查器(非常简单),并且感到惊讶的是,我的inputStreamToString方法仅次于需要发出HTTP请求的方法,这在时间上仅次于需要发出HTTP请求的方法.当前的定义是这样的:

So I was running a profiler on my (admittedly pretty simple) application in Java, and was surprised that second only to methods that required making HTTP requests in terms of time was my inputStreamToString method. It's currently defined like this:

public static String inputStreamToString(InputStream in) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    in.close();
    return sb.toString();
}

如何使它更快? (是的,我确实确实需要字符串,并且不,InputStrings没那么大,而且,不,该方法的调用频率比程序中的大多数方法要少,而且,没有,我没有办法避免这种需要.转化.)

How can I make this faster? (And yes, I really do need strings, and no, the InputStrings aren't that large, and no, this method is being called less frequently than most methods in the program, and no, I there is no way to avoid the need of conversion.)

推荐答案

好吧,这就是所有I/O发生的地方(我假设探查器包括了readLine()等待数据进入的所有时间) .您唯一可以做的就是用足够大的缓冲区预初始化StringBuilder,这样就不必重新分配内存,但是我想在读取数据之前,一切都变得微不足道了.

Well, that's where all the I/O happens (I assume that the profiler includes all the time readLine() takes to wait for the data to come in). The only obvious thing you could do is to preinitialize the StringBuilder with a sufficiently large buffer so it doesn't have to reallocate memory, but I suppose that everything is dwarved by the time it takes to read data.

除此之外-您受I/O约束.通过网络接收数据只需花费时间.

Other than that - you're I/O bound. It simply takes time to receive data through the network.

也可以包括casablanca的评论:除了逐行阅读然后添加换行符之外,您还可以使用带有提供的相当大缓冲区的简单阅读器,并且仅对所有内容进行块读取.无需逐行读取,因为您似乎始终只是复制整个输入数据.手动逐行进行操作的唯一原因是是否要将换行符(如\r\n)标准化为标准的\n.

May as well include casablanca's comment too: Instead of reading line-by-line and then adding a newline, you may as well use a simple reader with a reasonably big buffer that you provide and just block-read everything. There's no need to read line-by-line since you seem to just copy the entire input data anyway. The only reasoning for manually going line-by-line is if you wanted to normalize the newlines (like \r\n) to a standard \n.

这篇关于Java中有效的字符串流输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆