[英]Why is copying a stream and then deserializing using a BinaryFormatter faster than just deserializing
此代碼大約需要8秒,其中包含來自數據庫中blob的大約65K的流
private string[] GetArray(Stream stream)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
object result = binaryFormatter.Deserialize(stream);
return (string[])result;
}
這段代碼需要幾毫秒:
private string[] GetArray(Stream stream)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();
Copy(stream, memoryStream);
memoryStream.Position = 0;
object result = binaryFormatter.Deserialize(memoryStream);
return (string[])result;
}
為什么?
所以你說當數據庫被取出時,問題就消失了。 這是我的理論:
BinaryFormatter
以微小的增量從流中讀取。 它必須盡可能少地讀取,以便它不會在序列化對象之后意外地吞下幾個字節。 這意味着它發出了大量的讀命令(我用Reflector驗證了這一點)。
可能每次讀取blob流都會導致網絡往返(或其他一些主要開銷)。 如果立即使用BinaryFormatter
,那將為您提供數百萬次往返。
緩沖首先使網絡更有效地利用,因為讀緩沖區大小要大得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.