Optimization of java.io.DataInputStream

Alex Yursha alexyursha at gmail.com
Tue Nov 12 08:43:50 UTC 2013


The following methods in java.io.DataInputStream perform right shift to
zero positions in their implementations:
- short readShort()
- int readUnsignedShort()
- char readChar()
- int readInt()
- long readLong()
- String readUTF(DataInput in)

For example:

    public final short readShort() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
       return (short)((ch1 << 8) + *(ch2 << 0)*);
    }

It can be optimizied as follows:

    public final short readShort() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (short)((ch1 << 8) + *ch2*);
    }


This optimization saves 2 bytecode instructions in the class file code
arrays of each method mentioned above.



More information about the core-libs-dev mailing list