这很可能只是一个 KISS 时刻,但我觉得无论如何我都应该问。
我有一个线程,它正在从套接字 InputStream 读取。由于我正在处理特别小的数据大小(因为我可以期望接收的数据是 100 - 200 字节的顺序),我将缓冲区数组大小设置为 256。作为我的读取功能的一部分,我有一个检查这将确保当我从 InputStream 中读取所有数据时。如果我没有,那么我将再次递归调用 read 函数。对于每个递归调用,我将两个缓冲区数组重新合并在一起。
我的问题是,虽然我从没想过会使用超过 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 并称之为完成?