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

查看:33
本文介绍了您如何决定用于 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 与来自磁盘的 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天全站免登陆