Reading performance of one byte compared to many at a time?

I am trying to compare InputStream.read() vs InputStream.read(byte[] b) in terms of performance.

Is InputStream.read(byte[] b) faster somehow, given the read(b, off, len) method for the InputStream class, does the read() method call again?

+7
source share
2 answers

Do not confuse what the default behavior of InputStream is and what most of its subclasses do. The principle of OO design is that subclasses can change the behavior of a method for this implementation.

From InputStream - read (byte []) repeatedly calls read ().

 public int read(byte b[], int off, int len) throws IOException { // code removed for (; i < len ; i++) { c = read(); // code removed } 

From BufferedInputStream - read (byte []) does not call read ().

 public synchronized int read(byte b[], int off, int len) throws IOException { // code removed int nread = read1(b, off + n, len - n); // code removed } private int read1(byte[] b, int off, int len) throws IOException { // code removed return getInIfOpen().read(b, off, len); // code removed } 

From FileInputStream - read (byte []) does not call read ().

 public int read(byte b[], int off, int len) throws IOException { return readBytes(b, off, len); } private native int readBytes(byte b[], int off, int len) throws IOException; 

While an InputStream will read one byte at a time, almost all implementations pass read (byte []) to the same method in the base stream.

Note: read implementations (byte [], int, int) are different in all three cases.

What I want to say more clearly is: Let's say I want to read 20 bytes, Reading one byte at a time gets into the base stream (for example, the file system) every time in the loop, which means 20 times. an array of 20 bytes at a time, i.e. using read (byte [] 20). Now, to get into the base stream (for example, the file system) once or 20 times .. ?? (since it is given: read (byte [] b) the method will also call the read () method again 20 times)

If you use BufferedInputStream or FileInputStream, a single read (byte []) results in the system call itself to read in bytes [].

+4
source

Use whatever you find most convenient in your case, but remember to wrap the InputStream with a BufferedInputStream .

Without buffering, a single read() will delete the main stream (e.g. the file system) every time you read. When buffering, the same read() loads a piece (e.g. 4KiB) and buffers it. Obviously, reading from disk (even with some caching of the OS or hard disk) is much slower.

Therefore, read(byte[] b) better only if your stream is not buffered - or if you really want to read more than one byte.

+2
source

All Articles