哪种内存更好? 哪个内存消耗较低?
byte[] Pic = (byte[])re.GetValue(4);
MemoryStream MS = new MemoryStream();
MS.Write(Pic, 0, Pic.Length);
pictureBox1.BackgroundImage = Image.FromStream(MS);
或
pictureBox1.BackgroundImage = Image.FromStream(new MemoryStream((byte[])re.GetValue(4), true));
答案 0 :(得分:2)
第二个将更快地工作,它将使用更少的内存。从构造函数初始化MemoryStream
时,只是分配给内部缓冲区的字节(流将不可调整大小):
public MemoryStream(byte[] buffer, bool writable)
{
_buffer = buffer;
_writable = writable;
_exposable = false;
}
如果使用无参数构造函数,则可以使用初始容量0
调整流的大小。在写入期间,将创建新的字节数组,并将值复制到内部缓冲区:
public MemoryStream()
{
_buffer = new byte[0];
_writable = true;
_exposable = true;
}
public override void Write(byte[] buffer, int offset, int count)
{
// EnsureCapacity
byte[] dst = new byte[_position + count];
Buffer.InternalBlockCopy(_buffer, 0, dst, 0, _length);
_buffer = dst;
// Copy
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
}