java - 如何提高读取 InputStream 的性能?

标签 java sockets merge arrays bytebuffer

这很可能只是一个 KISS 时刻,但我觉得无论如何我都应该问。

我有一个线程,它正在从套接字输入流读取。由于我处理的数据量特别小(如我期望接收的数据大小约为 100 - 200 字节),因此我将缓冲区数组大小设置为 256。作为读取函数的一部分,我有一个检查这将确保当我从 InputStream 读取时获得所有数据。如果我没有这样做,我将再次递归调用读取函数。对于每个递归调用,我将两个缓冲区数组重新合并在一起。

我的问题是,虽然我从未预期使用超过 256 的缓冲区,但我想保证安全。但是,如果羊开始飞并且缓冲区显着增加,则读取函数(根据估计)将开始花费更多时间才能完成指数曲线。

如何提高读取功能和/或缓冲区合并的效率?

这是当前的读取函数。

int BUFFER_AMOUNT = 256;

private int read(byte[] buffer) throws IOException {
   int bytes = mInStream.read(buffer); // Read the input stream

   if (bytes == -1) { // If bytes == -1 then we didn't get all of the data

        byte[] newBuffer = new byte[BUFFER_AMOUNT]; // Try to get the rest
        int newBytes;
        newBytes = read(newBuffer); // Recurse until we have all the data

        byte[] oldBuffer = new byte[bytes + newBytes]; // make the final array size

        // Merge buffer into the begining of old buffer.
        // We do this so that once the method finishes, we can just add the 
        // modified buffer to a queue later in the class for processing.
        for (int i = 0; i < bytes; i++) 
            oldBuffer[i] = buffer[i];

        for (int i = bytes; i < bytes + newBytes; i++) // Merge newBuffer into the latter half of old Buffer
            oldBuffer[i] = newBuffer[i];
        // Used for the recursion

        buffer = oldBuffer; // And now we set buffer to the new buffer full of all the data.
        return bytes + newBytes;
    }
    return bytes;
}

编辑:我是否偏执(不合理)并且应该将缓冲区设置为 2048 并称之为完成?

最佳答案

BufferedInputStream,如 Roland 所说,以及 DataInputStream.readFully(),它替换了所有循环代码。

关于java - 如何提高读取 InputStream 的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6541034/

相关文章:

c# - NetworkStream 是否有 .ReadLine() 函数或类似的函数?

python - 基于列插值加入 Pandas

python - 如何在 Python 中合并 200 个 csv 文件

Windows系统文件的Java和NTFS权限

java - 使用 Bloomberg API 绘制历史最新价格图表

perl - 使用 select 来轮询连接 - TCP 服务器

java - java.mail 和套接字的问题

mercurial - Mercurial:将单个更改 merge 到一个未命名的分支中

java - 将 JSON 值数组解析为 POJO

java - 在 MacOS 上使用 JDK 7 显示启动屏幕时,我的 java 启动器崩溃