Asymmetry between FilterInputStream and FilterOutputStream

For some reason, I recently started using FilterInputStream and FilterOutputStream as a convenient basis for subclasses of InputStream and OutputStream. Narrowing down a brand new serious performance issue in my code, I found that while FilterInputStream redirected read(byte[], int, int) to an identical invocation on its backing InputStream, FilterOutputStream redirected write(byte[], int, int) to a loop of calls to write(int), which is, depending on the OutputStream backing it (sockets/files), extremely inefficient.

Don’t let it byte you!

Code snippets from java.io.*


public class FilterInputStream extends InputStream {
    public int read(byte b[], int off, int len) throws IOException {
	return in.read(b, off, len);
    }
}


public class FilterOutputStream extends OutputStream {
    public void write(byte b[], int off, int len) throws IOException {
	if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
	    throw new IndexOutOfBoundsException();

	for (int i = 0 ; i < len ; i++) {
	    write(b[off + i]);
	}
    }
}