Java中的流如何影响内存消耗? [英] How does streams in Java affect memory consumption?

查看:167
本文介绍了Java中的流如何影响内存消耗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用流媒体很多次,但我从来没有读过很多关于它们实际工作的信息。除了流只是一个比喻之外,我也不太了解它们。流只表示字节序列。我不太了解它们实际上是如何工作的,我想在Java中打开一个文件流与具有向流提供指针功能的操作系统进行交互。

I have been using streams many times but I never read much about how they actually works. Nor do I know much about them other than that a stream is just a metaphor. A stream only represent a sequence of bytes. I don't know much about how they actually work, I guess opening a file stream in Java interact with the OS that have the functionality to give a "pointer" to a stream.

基本上我的问题是流如何影响内存消耗。例如,当你有一个输入流并开始从它读取时,你只会开始增加内存消耗,读取的字节数是多少?在Java中打开流时,在开始阅读之前,实际上并没有加载完整的文件?如果您从一个流中读取并直接写入另一个流,则只会增加内存的读取字节数(可能还有缓冲区)?如果你在java中读取一个字节数组的字节,那么你会增加文件大小的内存消耗?

Basically my question is how streams affect memory consumption. When you have for instance a input stream and you start reading from it you only start increasing the memory consumption with the amount of bytes read? When opening a stream in Java you don't actually load the full file before you start reading? If you read from one stream and directly write to another stream you only increase the memory with the amount of bytes that you read (and potentially have in buffer)? If you read bytes to an byte array in java then you increase the memory consumption with the size of the file?

可能听起来像一个奇怪的问题,但我可能需要一些指导/纠正我的理解。谢谢。

May sound like an odd question but I could need some guidance/correction on my understanding. Thanks.

推荐答案

从<$ c $开始阅读后几乎没有内存开销C>的InputStream 。用于打开文件的操作系统开销非常小,而在JVM中用于新对象分配的开销很小。如果使用 BufferedInputStream ,默认情况下为8KB,也可能会产生很小的开销。

There is almost no memory overhead after you start reading from the InputStream. There is very small OS-overhead for opening a file and a tiny overhead in the JVM for new object allocation. There also might be a small overhead in case you use BufferedInputStream which is 8KB by default.

写入的开销在很大程度上取决于你写的地方。如果它是 FileOutputStream ,那么它与上面描述的相同。如果它是 ByteArrayOutputStream ,那么在最好的情况下它是(2 *流长度)字节,在最坏的情况下是(3 *流长度)字节场景。即将10k字节从 InputStream 复制到字节数组中,在最坏的情况下将分配30k字节。

The overhead for writing very much depends on where you write to. If it's a FileOutputStream, then it's the same as described above. If it's a ByteArrayOutputStream, then it's (2 * stream length) bytes in the best case and (3 * stream length) bytes in the worst case scenario. I.e. to copy 10k bytes from an InputStream into a byte array 30k bytes will be allocated in the worst case.

原因是 ByteArrayOutputStream 在达到限制后大小增长2倍,当你调用 toByteArray()

The reason for this is that ByteArrayOutputStream size growth 2 times after it's limit is reached and it also allocates a new buffer when you call toByteArray().

这篇关于Java中的流如何影响内存消耗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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