关于MemoryStream的GetBuffer和ToArray函数

System.IO下的MemoryStream使用频率也不低, 通常被用来将其它Stream对象快速读取以转换成字节(byte)数组的存储载体. 比如下面的MemoryStream代码:
public const int UNIT_MEGABYTE = 0x100000;

public static byte[] ReadStreamToBytes(Stream stream) {
    if (stream == null && !stream.CanRead)
        return null;
    if (stream is MemoryStream)
        return ((MemoryStream)stream).GetBuffer();
    using (MemoryStream memStream = new MemoryStream((int)stream.Length)) {
        stream.Position = 0;
        byte[] block = new byte[UNIT_MEGABYTE];
        while (true) {
            int read = stream.Read(block, 0, UNIT_MEGABYTE);
            if (read < 1)
                break;
            memStream.Write(block, 0, read);
        }
        return memStream.GetBuffer();
    }
}
我见过不少人也包括自己习惯获得MemoryStream的字节数组使用它的ToArray函数. 却忽略了GetBuffer函数. 两者的区别显而易见: ToArray返回字节数组的Copy, GetBuffer则返回MemoryStream内部维护和使用的字节数组. 许多情况下我们只是要使用字节数组, 并非真正需要创建它的副本. 使用ToArray增加了资源开销.

MemoryStream GetBuffer Function:
public virtual byte[] GetBuffer()
{
    if (!this._exposable)
    {
        throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
    }
    return this._buffer;
}

MemoryStream ToArray Function:
public virtual byte[] ToArray()
{
    byte[] dst = new byte[this._length – this._origin];
    Buffer.InternalBlockCopy(this._buffer, this._origin, dst, 0, this._length – this._origin);
    return dst;
}

This entry was posted in .NET. Bookmark the permalink.

Leave a comment