此代码大约需要 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
,这将为您提供数百万次往返。
缓冲首先使网络得到更有效的利用,因为读取缓冲区的大小要大得多。
关于c# - 为什么复制流然后使用 BinaryFormatter 反序列化比仅仅反序列化更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232041/