java - Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream? -
i trying read file array using fileinputstream, , ~800kb file took 3 seconds read memory. tried same code except fileinputstream wrapped bufferedinputstream , took 76 milliseconds. why reading file byte byte done faster bufferedinputstream though i'm still reading byte byte? here's code (the rest of code entirely irrelevant). note "fast" code. can remove bufferedinputstream if want "slow" code:
inputstream = null; try { = new bufferedinputstream(new fileinputstream(file)); int[] filearr = new int[(int) file.length()]; (int = 0, temp = 0; (temp = is.read()) != -1; i++) { filearr[i] = temp; }
bufferedinputstream on 30 times faster. far more that. so, why this, , possible make code more efficient (without using external libraries)?
in fileinputstream
, method read()
reads single byte. source code:
/** * reads byte of data input stream. method blocks * if no input yet available. * * @return next byte of data, or <code>-1</code> if end of * file reached. * @exception ioexception if i/o error occurs. */ public native int read() throws ioexception;
this native call os uses disk read single byte. heavy operation.
with bufferedinputstream
, method delegates overloaded read()
method reads 8192
amount of bytes , buffers them until needed. still returns single byte (but keeps others in reserve). way bufferedinputstream
makes less native calls os read file.
for example, file 32768
bytes long. bytes in memory fileinputstream
, require 32768
native calls os. bufferedinputstream
, require 4
, regardless of number of read()
calls (still 32768
).
as how make faster, might want consider java 7's nio filechannel
class, have no evidence support this.
Comments
Post a Comment