[英]C# MemoryStream is larger than FileStream
我有一個壓縮字節數組的方法。 我使用內存流和文件流進行測試。 即使相同的方法,memorystream的結果也更大,誰能解釋為什么?
public byte[] DeflateCompress(byte[] data2Compress)
{
using (FileStream _fileToCompress = File.Create("_deflatecompressed.bin"))
{
using (DeflateStream _compressionStream = new DeflateStream(_fileToCompress, CompressionMode.Compress))
{
_compressionStream.Write(data2Compress, 0, data2Compress.Length);
_compressionStream.Close();
}
}
return File.ReadAllBytes("_deflatecompressed.bin");
}
public byte[] DeflateCompress(byte[] data2Compress)
{
using (MemoryStream _memStreamCompress = new MemoryStream())
{
using (DeflateStream _defalteStreamCompress = new DeflateStream(_memStreamCompress, CompressionMode.Compress))
{
_defalteStreamCompress.Write(data2Compress, 0, data2Compress.Length);
_defalteStreamCompress.Close();
}
return _memStreamCompress.GetBuffer();
}
}
如果我將輸出字節數組寫入一個文件,則使用memorystream創建的字節數組會更大。
MemoryStream.GetBuffer()
將返回完整的內部緩沖區,該緩沖區可以大於數據。 根據需要調整大小。 當您超過緩沖區容量時,內部緩沖區大小將增加一倍。
如果需要將MemoryStream
轉換為僅包含數據的字節數組,請使用MemoryStream.ToArray()
。 它將創建一個足夠大的新數組,並將相關的緩沖區內容復制到其中。
正如MSDN所說:
請注意,緩沖區包含分配的字節,這些字節可能未使用。 例如,如果將字符串
"test"
寫入MemoryStream
對象,則從GetBuffer
返回的緩沖區的長度為256
而不是4
,並且未使用252
個字節。 要僅獲取緩沖區中的數據,請使用ToArray
方法。 但是,ToArray
會在內存中創建數據的副本。
如果您想從緩沖區中讀取一個塊,而不必關心大小是否完全不匹配,則GetBuffer
函數很有用。 ToArray
較慢,因為它必須在每次調用時復制整個緩沖區的內容,而GetBuffer
只會簡單地返回對該緩沖區的引用。
例如,如果使用諸如Stream.Write
方法,則GetBuffer
可能非常有用:
public abstract void Write(
byte[] buffer,
int offset,
int count
)
框架中有很多地方都有這樣的重載,它們需要一個緩沖區,但只能處理其中的一部分。
MemoryStream在內部使用字節數組。 在需要時會加倍。
因此,它可能具有未使用字節的TON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.