第二个会工作得更快,它会使用更少的内存。当您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);
}