MemoryStream 与字节数组
在使用 MemoryStream 时,我发现自己经常将数据复制(因此复制)到临时字节数组中。
我认为这有点浪费资源,因为 MemoryStream 不允许您直接访问底层字节数组。
在这种情况下,MemoryStream 的真正优势是什么? 我在某处读到它的作用就像内存映射文件。 仅在访问时从磁盘获取数据,消耗更少的内存。
真的吗? 我不这么认为。 也许这是 FileStream 的情况?
感谢您的澄清。
While using a MemoryStream, I find myself often copying (hence duplicating) data to a temporary array of bytes.
I think it's a little bit of a waste of ressource, because MemoryStream dosen't let you directly access the underlying byte array.
In this situation, what's the real advantage of a MemoryStream? I have read somewhere that it acts like a memory-mapped file. Data is brought from disk only on access, consuming less memory.
Is that true? I don't think so. Maybe it's the case for a FileStream?
Thank you for your clarification.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,内存流的主要优点是它动态增长,并为此进行了优化。 必须将其复制出来并复制内存是一件痛苦的事情,但是如果您主要使用它是构建一个要在进程结束时传递的缓冲区,那么该缺陷会在一定程度上得到缓解。
我应该补充一点,与 FileStream 相比,MemoryStream 速度要快得多。 它们的大小比 FileStream 更受限制,因为磁盘空间通常比 RAM 大得多。 所以你必须决定你需要速度还是空间。
For me, the primary advantage of a memory stream is that it grows dynamically, and is optimized to do so. It is a pain to have to copy it out and duplicate memory, but if you primary use of it is to construct a buffer to be handed off at the end of the process, that flaw is amortized somewhat.
I should add, as opposed to a FileStream, MemoryStreams are much, much faster. They are more limited in size than FileStreams, because you generally have vastly more disk space than RAM. So you have to decide whether you need speed or space.
您可以使用 getBuffer 函数(但前提是您从提供的字节数组创建了 MemoryStream,如果您希望能够直接操作缓冲区,这很有用)
使用 MemoryStream 的唯一优点是,如果您使用的 API 是基于流,如果您需要字节缓冲区能够动态增长..
You can get the underlying byte buffer using the getBuffer function (but only if you created the MemoryStream from a byte array that you provided, which is useful if you want to be able to manipulate the buffer directly)
The only advantage to using a MemoryStream is if you're using an API that's based on streams, of if you need the byte buffer to be able to grow dynamically..