MemoryStream 和深度克隆
我在我的方法之一中使用 MemoryStream 作为深度克隆。我调用该方法几次,我注意到调用它的次数越多,它就越减慢我的程序。当我停止使用内存流时,有没有办法每次都清除内存流?
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
I am using MemoryStream as deep cloning in one of my methods. I call that method a few times, and I notice the more I call it the more it slows my program. Is there a way to clear the memory stream each time, when I stop using the memory stream?
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
内存流在每次调用的 using 语句末尾处被释放。然而,它可能要等到稍后才会被垃圾收集。我不认为潜在的内存使用是你的问题。如果您在调用之间发现明显的速度差异,我认为您每次都必须序列化一个更复杂的对象。 添加诊断语句
如果您在调用
Serialize()
之后 ,它会每次报告相同的数字还是增加大小?如果大小增加,则每次都会序列化更大的对象图,并且速度会减慢。The memorystream is Disposed at the end of the using statement every call. It may not be garbage collected until later however. I don't think that potential memory use is your problem though. If you get noticable speed differences between calls, I think you must be serializing a more complicated object each time. If you ad a diagnostic statment such as
after your call to
Serialize()
, will it report the same number every time, or increasing size? If the size increases, then you are serializing a larger object graph each time, and the slowdown is expected.