0

I have the following code to download from the internet

 URLConnection    ucon = url.openConnection();
 InputStream is = ucon.getInputStream();
 BufferedInputStream inStream = new BufferedInputStream(is, 8192);//this is value one 
 FileOutputStream outStream = new FileOutputStream(new File(location));
 byte[] buff = new byte[8192];//this is value two 

 int len;

 while ((len = inStream.read(buff)) != -1) {
     outStream.write(buff, 0, len);          
 }

My question is what happens if I change the the buffer value : value one and two how does the download speed change ? should they be the same value ? if they are not the same what should each of them indicate ?

I have read the following post :

How do you determine the ideal buffer size when using FileInputStream?

but I did not really understand it . can someone explain it for my please

Community
  • 1
  • 1
hash-set
  • 186
  • 1
  • 12
  • value two [if large enough] is the only one that you should care about. You can drop the `BufferedInputStream` because you're otherwise copying from a buffer into a buffer and that's a pointless extra operation that only slows down. Or just leave it as is. Should work fine. http://howtodoinjava.com/2014/12/10/how-java-io-works-internally-at-lower-level/ – zapl Nov 03 '15 at 17:59
  • @zapl That's not exactly true. While an additional buffer is unnecessary, you have no idea if `is` is buffered or not. It's also irresponsible to claim that it would "slow down" simply because there's a second buffer in between. Memory to memory copy is so quick that you could put 10 `BufferedInputSterams` in there and it wouldn't matter since the time is taken in the network communication, not the internal buffers. – Kayaman Nov 03 '15 at 18:06
  • 1
    As first approximation, larger buffer = faster. But its not linear, its asymptotic. If you Benchmark from the smallest possible size (1 byte) to any reasonable size (e.g. 2^20 = 1MB) you'll find that doubling the buffer size from 1b to 2b has a large effect, but doubling from 512k to 1024k yields neglible advantages. 8k is a reasonable compromise between memory consumption and speed. Deviating from it towards larger buffer gains you very little and making the buffer smaller frees very little memory. Stick with 8k, its the default size for exactly that reason. – Durandal Nov 03 '15 at 18:10
  • @zapi Like most buffered I/O systems I have ever used, `BufferedInputStream` is smart enoguh to avoid double copying. – user207421 Nov 03 '15 at 18:14
  • The only thing a `BufferedInputStream` does in practice is to make multiple `read(byte[]` calls in case the underlying input stream does not provide a full buffer in a single `read(byte[]` call. The benefit is that you get predictable output chunks to write. May or may not provide a benefit but it's most likely not going to matter because most input streams will not produce underfull buffers anyways. – zapl Nov 03 '15 at 18:25

0 Answers0