これはキスの瞬間かもしれませんが、とにかく尋ねるべきだと思います。
スレッドがあり、ソケットの InputStream から読み取っています。特に小さいデータ サイズを扱っているため (受信できるデータが 100 ~ 200 バイトのオーダーであるため)、バッファー配列のサイズを 256 に設定しました。読み取り関数の一部として、 InputStream から読み取ったときに、すべてのデータを取得したことを確認します。そうでない場合は、読み取り関数を再帰的に呼び出します。再帰呼び出しごとに、2 つのバッファー配列をマージして元に戻します。
私の問題は、256 を超えるバッファーを使用することは決して予想していませんが、安全を確保したいということです。しかし、ヒツジが飛び始め、バッファーが読み取りよりも大幅に多い場合、関数は (推定により) 完了するまでに指数関数的な曲線を取り始めます。
読み取り機能やバッファ マージの効率を上げるにはどうすればよいですか?
これがそのままの read 関数です。
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に設定して完了と呼ぶべきですか?