我想知道在字节数组和流(特别是使用 MemoryStream.ToArray()
和 MemoryStream(byte[])
时的 MemoryStreams)之间转换时是否存在开销。我假设内存使用量暂时加倍。
例如,我读取为流,转换为字节,然后再次转换为流。 但是摆脱字节转换将需要一些重写。如果没有什么区别,我不想浪费时间重写它。
最佳答案
所以,是的..您假设 ToArray
复制流中的内存是正确的。
如果您不想这样做(出于效率原因),您可以直接在流中修改字节。看看这个:
// create some bytes: 0,1,2,3,4,5,6,7...
var originalBytes = Enumerable.Range(0, 256).Select(Convert.ToByte).ToArray();
using(var ms = new MemoryStream(originalBytes)) // ms is referencing bytes array, not duplicating it
{
// var duplicatedBytes = ms.ToArray(); // copy of originalBytes array
// If you don't want to duplicate the bytes but want to
// modify the buffer directly, you could do this:
var bufRef = ms.GetBuffer();
for(var i = 0; i < bufRef.Length; ++i)
{
bufRef[i] = Convert.ToByte(bufRef[i] ^ 0x55);
}
// or this:
/*
ms.TryGetBuffer(out var buf);
for (var i = 0; i < buf.Count; ++i)
{
buf[i] = Convert.ToByte(buf[i] ^ 0x55);
}*/
// or this:
/*
for (var i = 0; i < ms.Length; ++i)
{
ms.Position = i;
var b = ms.ReadByte();
ms.Position = i;
ms.WriteByte(Convert.ToByte(b ^ 0x55));
}*/
}
// originalBytes will now be 85,84,87,86...
预计到达时间:
编辑添加 Blindy 的示例。谢谢! -- 完全忘记了 GetBuffer
并且不知道 TryGetBuffer
关于c# - byte[] 和 MemoryStream 之间的转换会产生开销吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63637874/