管理内存流的内存

时间:2012-07-24 14:37:16

标签: c# memory memorystream

哪种内存更好? 哪个内存消耗较低?

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));

1 个答案:

答案 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);
}