你如何决定用于InputStream.read()的byte []大小? [英] How do you decide what byte[] size to use for InputStream.read()?

查看:242
本文介绍了你如何决定用于InputStream.read()的byte []大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从InputStreams读取时,如何确定byte []的大小?

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 one I'm wondering about

while ((nRead = is.read(data, 0, data.length)) != -1) {
  ...do something..
}

你什么时候用一个小的对一个大的?有什么区别?数字是否需要以1024为增量?如果它是来自网络和磁盘的InputStream会有所不同吗?

When do you use a small one vs a large one? What are the differences? Does the number want to be in increments of 1024? Does it make a difference if it is an InputStream from the network vs the disk?

非常感谢,我似乎无法在其他地方找到明确的答案。

Thanks much, I can't seem to find a clear answer elsewhere.

推荐答案

大多数人使用2的幂来表示大小。
如果缓冲区至少为512字节,则没有太大区别(<20%)

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

对于网络,最佳大小可以是2 KB到8 KB(底层数据包大小通常高达~1.5 KB)对于磁盘访问,最快的大小可以是8K到64 KB。如果您使用8K或16K,则不会有问题。

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.

注意网络下载,您可能会发现通常不使用整个缓冲区。对于99%的用例而言,浪费几KB并不重要。

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.

这篇关于你如何决定用于InputStream.read()的byte []大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆