Domanda

I know wrapping BufferedInpurStream around FileInputStream makes read operation faster but trying to figure out how.I looked in to source code of BufferedInpurStream and got some stuff. Here is my understanding

InputStream in = new BufferedInpurStream(new FileInputStream(filename));
  int byteToRead;
  while((byteToRead = in.read()) != -1)

when i do bufferedInpurStream.read() , Internally ,it will first read the chunk of bytes at a time in to buffer and then read each byte one by one from buffer instead of reading it from file(which is costlier).Once that buffer is empty it will fill it again with chunk of bytes

while with FileInputStream.read() , read operation is performed for each byte one by one from file which is very costly

Is this understanding correct?

È stato utile?

Soluzione

Typically, read(byte[] b) (or read(byte[] b, int off, int len)) is prefered than read(), because it might have some IO performance advantages.

And if you use read(byte[] b), BufferedInpurStream have no acutal advantages, as long as you use same buffer sizes.

void read(InputStream inputStream, int bufferSize) throws IOException
{
    byte[] buffer = new byte[bufferSize];
    int read;
    while ((read = inputStream.read(buffer)) != -1)
    {
       // do some work
    }
}

and

void read2(InputStream inputStream, int bufferSize) throws IOException
{
    BufferedInputStream bis = new BufferedInputStream(inputStream, bufferSize);
    try
    {
        byte[] buffer = new byte[bufferSize];
        int read;
        while ((read = bis .read(buffer)) != -1)
        {
            // do some work
        }
    }
    finally
    {
        bis.close();
    }
}

try read and read2. you will find out that as long as you use appropriate buffer size, Wrapping to BufferedInputStream makes no performance improvements. (acutally it makes another computational costs...)

So, when do you need BufferedInputStream? Here is my suggest :

  • If you know "appropriate" buffer size, just handle it directly. It produces shorter code. (ex: File reading. you can use file size as a buffer size.)
  • If you don't know "appropriate" buffer size or you have to pass the InputStream to another library, wrap the stream as an BufferedInputStream. you may benefit from buffering. (ex: Web file transfer. server may not provide content-length field.)

Altri suggerimenti

Yes. As you described, BufferedInputStream greatly reduces the number of IO calls made while reading one byte at a time from a stream (since most of those read() calls hit the buffer instead).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top