C#中的MemoryStream VS字节数组 [英] c# MemoryStream vs Byte Array

查看:113
本文介绍了C#中的MemoryStream VS字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,即生成并返回一个MemoryStream。后一代的MemoryStream的大小是固定的,我不需要写它了唯一的输出是必需的。写MailAttachment或写入数据库的例子。

I have a function, which generates and returns a MemoryStream. After generation the size of the MemoryStream is fixed, I dont need to write to it anymore only output is required. Write to MailAttachment or write to database for example.

什么是到手的对象周围的最好方法是什么? MemoryStream的或字节数组?如果我使用的MemoryStream我必须重新读取后的位置。

What is the best way to hand the object around? MemoryStream or Byte Array? If I use MemoryStream I have to reset the position after read.

推荐答案

如果您需要保留在内存中的所有数据,然后在很多方面的选择是任意的。如果已有code的上操作 的,那么的MemoryStream 可能更方便,但如果你返回字节[] 您可以随时只是包装在一个新的MemoryStream(BLOB) 反正的。

If you have to hold all the data in memory, then in many ways the choice is arbitrary. If you have existing code that operates on Stream, then MemoryStream may be more convenient, but if you return a byte[] you can always just wrap that in a new MemoryStream(blob) anyway.

这可能还取决于它有多大和多久,你持有它; 的MemoryStream 可以的超大的,这有利也有弊。它强制到字节[] 如果你持有的数据了,而可能是有用的,因为它会修剪掉多余的;但是,如果你只是保持它的简单,它可能是适得其反,因为它会迫使你的重复的大多数(在绝对最低:半)的数据,同时创建新的副本。

It might also depend on how big it is and how long you are holding it for; MemoryStream can be oversized, which has advantages and disadvantages. Forcing it to a byte[] may be useful if you are holding the data for a while, since it will trim off any excess; however, if you are only keeping it briefly, it may be counter-productive, since it will force you to duplicate most (at an absolute minimum: half) of the data while you create the new copy.

所以,这取决于很多方面,使用情况和意图。在大多数情况下,任何作品,并且是简单明了的就足够了。如果数据特别大,持有较长时间,可能要刻意调整了一点。

So; it depends a lot on context, usage and intent. In most scenarios, "whichever works, and is clear and simple" may suffice. If the data is particularly large or held for a prolonged period, you may want to deliberately tweak it a bit.

的一个额外的好处的字节[] 办法:如果需要的话,多个线程可以同时(只要他们读)安全地访问它 - 这是不正确的。对的MemoryStream 然而,这可能是一个错误的优势:最code不会的需要的访问字节[] 从多个线程

One additional advantage of the byte[] approach: if needed, multiple threads can access it safely at once (as long as they are reading) - this is not true of MemoryStream. However, that may be a false advantage: most code won't need to access the byte[] from multiple threads.

这篇关于C#中的MemoryStream VS字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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