How do you decide what byte[] size to use for InputStream.read()?

后端 未结 5 1631
生来不讨喜
生来不讨喜 2020-12-05 02:42

When reading from InputStreams, how do you decide what size to use for the byte[]?

int nRead;
byte[] data = new byte[16384]; // <-- this number is the o         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 03:07

    Most people use powers of 2 for the size. If the buffer is at least 512 bytes, it doesn't make much difference ( < 20% )

    For network the optimal size can be 2 KB to 8 KB (The underlying packet size is typically up to ~1.5 KB) For disk access, the fastest size can be 8K to 64 KB. If you use 8K or 16K you won't have a problem.

    Note for network downloads, you are likely to find you usually don't use the whole buffer. Wasting a few KB doesn't matter much for 99% of use cases.

提交回复
热议问题