Reputation: 3632
I read this question : Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream? According to author BufferedInputStream(BIS)
faster than FileInputStream(FIS)
because when method read()
is invoked in FileInputStream
it always does system call using native API in order to fetch single byte, while BufferedInputStream
does the same but it requires chunk of bytes from OS and stores them in local field called buf
which is declared inside BIS class and then when read()
is called BIS return byte from buf
array.
I looked through the code of BIS ,specifically read()
method and it doesn't clear for me when it happens,when BIS requires chunk of bytes instead of one. Method read()
firstly checks if (pos >= count)
If so it calls fill()
method which firstly checks that buf is not full , if buf has space then method of InputStream is called public int read(byte b[], int off, int len)
where b[] is our buffer , and inside of this method we can see that it makes system calls inside loop which is equal to len
param .
for (; i < len ; i++) {
c = read();
Did i miss something or both classes BIS and FIS will do the same amount of system calls in order to fetch each byte separately ?
Upvotes: 2
Views: 404
Reputation: 5052
You are looking in the wrong place.
InputStream provides implementation of int read(byte[] b, int off, int len)
which indeed invokes read()
in a loop. So if a concrete InputStream wrapped by BuffredInputStream does not override this method, then there will be no performance improvement. However, the question you linked talks specifically about FileInputStream which does override this method by invoking native int readBytes(byte b[], int off, int len)
.
Upvotes: 2