0

哪个更适合内存?哪个内存消耗低?

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

1 回答 1

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);
}
于 2012-07-24T14:44:14.193 回答